Using ViewModifier
in SwiftUI allows us to use to apply the same styles on different elements wihtout repeating ourselves (DRY). Most importantly if you need to change anything it is enough to modify it once.
Usually we write style Text
in the following way:
Text("Header")
.font(.largeTitle.bold())
.foregroundColor(Color.accentColor)
If we want to apply it again, we need to retype… Instead the better idea to use ViewModifier
.
struct Header: ViewModifier {
func body(content: Content) -> some View {
content
.font(.largeTitle.bold())
.foregroundColor(Color.accentColor)
}
}
The content
represents our Text
view.
Text("Header")
.modifier(Header())
Of course, it can work on any kind of Views in SwiftUI. Enjoy.