Custom View Modifiers in SwiftUI
Last Run on XCODE 11.6 / Swift 5.2
In SwiftUI View(s) are the building blocks of the UI. All changes to the Views are done by calling special functions called modfiers that wrap up the original View with the needful changes and return a View back.
In the example below, we apply a few modifiers to a Text view to create the impression of a highlighted text.
Text("I ♥️ SwiftUI")
.font(.largeTitle)
.foregroundColor(.black)
.background(Color.yellow)
We can combine the above set of notifications into a single modifier. This requires us to construct a struct that conforms to the ViewModifier
protocol.
The ViewModifier
protocol requires implementing the body method that gets the current body of the caller in content.
func body(content: Self.Content) -> Self.Body
Here is our implementation of HighlightedText that conforms to the ViewModifier
protocol. It takes two optional parameters to configure the foreground and background color.
struct HighlightedText: ViewModifier {
var backgroundColor: Color = .yellow
var foregroundColor: Color = .black
func body(content: Content) -> some View {
content
.font(.largeTitle)
.foregroundColor(foregroundColor)
.background(backgroundColor)
}
init(backgroundColor: Color = .yellow, foregroundColor: Color = .black) {
self.backgroundColor = backgroundColor
self.foregroundColor = foregroundColor
}
}
Once we have a custom implementation of our View modifier, it can be called on our Text View using the modfifier method.
Text("I ♥️ SwiftUI")
.modifier(HighlightedText())
However, It would be nice to have our modifier also be called just like all the default available modifiers that come with SwiftUI. This can be simply achieved by extending the View class and add a method to it.
extension View {
func highlighter(backgroundColor: Color = .yellow, foregroundColor: Color = .black) -> some View {
return self.modifier(HighlightedText(backgroundColor: backgroundColor, foregroundColor: foregroundColor))
}
}
Finally, here is our modifier in action!
Text("I ♥️ SwiftUI")
.highlighter()
Text("I ♥️ SwiftUI")
.highlighter(backgroundColor: .green)
Text("I ♥️ SwiftUI")
.highlighter(foregroundColor: .pink)