iOS

Modifier- Environment Modifier & Regular Modifier

There are number of modifier which we we use for modify our view. We can apply the same modifier to many views at the same time. Example: if we have six Text() Views in VStack which we can modify applying directly that ...

J
Joynal Abedin
4
Modifier- Environment Modifier & Regular Modifier

There are number of modifier which we we use for modify our view. We can apply the same modifier to many views at the same time. Example:

if we have six Text() Views in VStack which we can modify applying directly that change apply to all six Text() Views.

struct ContentView: View {
    @State private var redBtnClick = false
    var body: some View {
        VStack {
            Text(\"Modifier One\")
            Text(\"Modifier Two\")
            Text(\"Modifier Three\")
            Text(\"Modifier Four\")
            Text(\"Modifier Five\")
            Text(\"Modifier Six\")
        }
 .font(.title)
.foregroundColor(.red)
    }
}

Output:

\"\"
Environment Modifier Output

Above this modifier called environment modifier & it's different from regular modifier. From coding perspective these modifier use same way regular modifier. But there are differently because if any of those child view override the same modifier, the child's version takes priority. Example:

Output:

struct ContentView: View {
    @State private var redBtnClick = false
    var body: some View {
        VStack {
            Text(\"Modifier One\")
                .foregroundColor(.green)
            Text(\"Modifier Two\")
            Text(\"Modifier Three\")
            Text(\"Modifier Four\")
            Text(\"Modifier Five\")
            Text(\"Modifier Six\")
        }
        .font(.title)
        .foregroundColor(.red)
    }
}
\"\"
environment modifier child's priority

There, foregroundColor() is an environment modifier, which means the \"Modifier One\" text view can override it with a custom color.

Other side regular modifier can not override the same Modifier in a child's view. Example:

struct ContentView: View {
    @State private var redBtnClick = false
    var body: some View {
        VStack {
            Text(\"Modifier One\")
                .blur(radius: 0)
            Text(\"Modifier Two\")
            Text(\"Modifier Three\")
            Text(\"Modifier Four\")
            Text(\"Modifier Five\")
            Text(\"Modifier Six\")
        }
        .blur(radius: 5)
    }
}

Output:

\"\"
Regular modifier

That won't work the same way: .blur() is a regular modifier. So any blurs applied to child views are added to the VStack blur rather than replacing it.

J

Written by Joynal Abedin

Passionate about technology, code, and sharing knowledge.

0 Comments

Leave a Comment