SwiftUI lets you modify the appearance or behavior of views by applying view modifiers to them. A view modifier takes a given view, modifies it, and returns a brand new view. This is really important to understand. Besides using the existing SwiftUI modifiers, you can create your own view modifier by conforming to the ViewModifier protocol and implementing its body method.
Combine multiple existing modifiers into single custom modifier
While working on SwiftUI projects, you might find yourself applying multiple view modifiers to the same views over and over again. For example, you might want to style certain text views in the same way (by adding a border to them) without duplicating the code.
First, create new struct called CustomTextBorder which conforms to the ViewModifier protocol. The only requirement of this protocol is to implement a body method which takes as an argument a view (content) which we wish to modify.
In our example we’re going to change the font of the text view, add some padding around it, add a border to it, and change the color of the entire view, all in a single modifier:
struct CustomTextBorder: ViewModifier {
func body(content: Content) -> some View {
return content
.font(.largeTitle)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 15)
.stroke(lineWidth: 2)
)
.foregroundColor(.blue)
}
}
Then, in order to apply the newly created modifier to a view, use the modifier() function on the view:
struct ContentView: View {
var body: some View {
Text("SwiftUI Tutorials")
.modifier(CustomTextBorder())
}
}
The result should look like this:
There is a better way to apply your custom view modifier to a view. Instead of using the modifier() function on the view, you can extend the View type with a custom method which applies your modifier directly to a view:
extension View {
func customTextBorder() -> some View {
return self.modifier(CustomTextBorder())
}
}
And then use it like this:
Text("SwiftUI Tutorials")
.customTextBorder()
Related tutorials:
- How to customize the appearance and behavior of UI elements in SwiftUI using modifiers
- How to add borders to SwiftUI views
Take a look at Apple’s official documentation of ViewModifier.