How to create custom modifiers
How to create custom modifiers êŽë š
Updated for Xcode 15
If you find yourself constantly attaching the same set of modifiers to a view â e.g., giving it a background color, some padding, a specific font, and so on â then you can avoid duplication by creating a custom view modifier that encapsulates all those changes. So, rather than say âmake it red, make it use a large fontâ and so on, you can just say âmake it look like a warning,â and apply a pre-made set of modifiers.
If you want to make your own, define a struct that conforms to the ViewModifier
protocol. This protocol requires that you accept a body(content:)
method that transforms some sort of content however you want, returning the result.
For example, this creates a new PrimaryLabel
modifier that adds padding, a red background, white text, and a large font, then uses it in a view:
struct PrimaryLabel: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.background(.red)
.foregroundStyle(.white)
.font(.largeTitle)
}
}
struct ContentView: View {
var body: some View {
Text("Hello, SwiftUI")
.modifier(PrimaryLabel())
}
}