SwiftUI ViewModifiers
Samuel Owino
Posted on June 4, 2022
A view modifier is a modifier that you apply to a view such as Text or Label or another modifier such as chained font() or foreground() producing a different version of the original modifier.
Protocol
protocol ViewModifier
Basic Usage
Text("Hello World!")
.bold()
.font(.title)
.foregoround(.yellow)
Creating a Custom View Modifiers
1 Create a struct that conforms to the ViewModifier Protocol
struct PrimaryTitleTextModifier: ViewModifier {}
2 Compose properties and return them as a view
struct PrimaryTitleStyle: ViewModifier {
func body(content: Content) -> some View {
content
.font(.title)
.padding()
.overlay {
RoundedRectangle(cornerRadius: 15)
.stroke(lineWidth: 6)
}
.foregroundColor(.black)
}
}
struct SecondaryTitleStyle: ViewModifier {
func body(content: Content) -> some View {
content
.font(.title3)
.padding()
.overlay {
RoundedRectangle(cornerRadius: 15)
.stroke(lineWidth: 6)
}
.foregroundColor(.gray)
}
}
3 Define an extension to View that itself integrates the new modifier
extension View {
func applyPrimaryTitleStyle() -> some View {
modifier(PrimaryTitleStyle)
}
}
4 Apply the property to any view like so...
Text("Tsavo National Park")
.applyPrimaryTitleStyle()
💖 💪 🙅 🚩
Samuel Owino
Posted on June 4, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.