SwiftUI ViewModifier

Arshad
2 min readDec 10, 2020

As the name suggests a ViewModifier is that you apply to a view or another view modifier.

The View is a simple protocol as you can see in its definition

public protocol View {
associatedtype Body : View
@ViewBuilder var body: Self.Body { get }
}

We have a associated type Body and a var for body.

Now ViewModifier is again a simple protocol with one required func

func body(content: Self.Content) -> Self.Body

Lets say we want to create a Text Label that should have a common style throughout the application. So we create a simple ViewModifier and apply some style on it as below.

struct SampleTitle: ViewModifier  {
func body(content: Content) -> some View {
content
.font(.title3)
.padding()
.foregroundColor(.blue)
.background(Color.green)
}
}

and than we create an extension for it

extension View {
func sampleTitleStyle() -> some View {
self.modifier(SampleTitle())
}
}

Now lets use this in the main ContentView

struct ContentView: View {
var body: some View {
VStack {
Text("Hello world")
.sampleTitleStyle()
}
}
}

As we can see above this style can be applied easily and reduces any clutter of the code.

We can also use property wrappers like @State, @Binding, @Environment etc. with the ViewModifier.

References

--

--