-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Swift 4 Programming Cookbook
By :
SwiftUI comes with built-in modifiers such as background() and fontWeight(), among others. It also gives you the ability to create your own custom modifiers. You can use custom modifiers to combine multiple existing modifiers into one.
In this section, we will create a custom modifier that adds rounded corners and a background to a Text view.
Create a new SwiftUI project named UsingViewModifiers.
Let’s create a view modifier and use a single line of code to apply it to a Text view. The steps are given here:
ContentView view with:
Text("Perfect")
ContentView.swift file, create a struct that conforms to the ViewModifier protocol, accepts a parameter of type Color, and applies styles to the view’s body:
struct BackgroundStyle: ViewModifier {
var bgColor: Color
func body(content: Content) -> some View{
content
.frame(width:UIScreen.main.bounds.width * 0.3)
.foregroundStyle(.black)
.padding()
.background(bgColor)
.cornerRadius(20)
}
}
modifier() modifier:
Text("Perfect").modifier(BackgroundStyle(bgColor:
.blue))
extension to the View protocol. The extension should be created outside the struct or Xcode will issue an error:
extension View {
func backgroundStyle(color: Color) -> some View{
self.modifier(BackgroundStyle(bgColor: color))
}
}
Text view with the backgroundStyle() modifier that you just created, which will add your custom styles:
Text("Perfect")
.backgroundStyle(color: Color.red)

Figure 1.15: Custom view modifier
This concludes the section on view modifiers. View modifiers promote clean coding and reduce repetition.
A view modifier creates a new view by altering the original view to which it is applied. We create a new view modifier by creating a struct that conforms to the ViewModifier protocol and apply our styles in the implementation of the required body function. You can make the ViewModifier customizable by requiring input parameters/properties that would be used when applying styles.
In the example here, the bgColor property is used in our BackGroundStyle struct, which alters the background color of the content passed to the body function.
At the end of Step 2, we have a functioning ViewModifier but decide to make it easier to use by creating a View extension and adding in a function that calls our struct:
extension View {
func backgroundStyle(color: Color) -> some View {
modifier(BackgroundStyle(bgColor: color))
}
}
We are thus able to use .backgroundStyle(color: Color) directly on our views instead of .modifier(BackgroundStyle(bgColor:Color)).
Apple documentation on view modifiers: https://developer.apple.com/documentation/swiftui/viewmodifier.