Instruction 2

View Modifiers

Another feature SwiftUI has that can be used to remove code duplication and create reusable code is View Modifiers…and you’ve been using it all this time! foregroundStyle(_:), padding(_:) and background(_:in:fillStyle:) are just a few of the many built-in modifiers SwiftUI has that you already use.

A view modifier is a way for you to apply some sort of transformation to the view. The view modifier padding(_:), for example, applies padding to a view’s frame, making it occupy more space.

Most view modifiers can be applied to any sort of view and even be applied to a collection of views. Consider the following code:

Vstack {
	Text(name)
	Text(surname)
	Text(age)
}

Here, you have a simple vertical stack with three labels. One for the user’s name, another for their surname, and the last one for their age. Now, if you want to change the font of these labels, you can use the view modifier font(_:) to do that. But instead of adding font(_:) to all of them, you can apply this modifier to the VStack.

Vstack {
	Text(name)
	Text(surname)
	Text(age)
}
.font(.headline)

This will apply the font headline to all three texts.

Using View Modifiers to Remove Code Duplication

SwiftUI allows you to create your own custom view modifier. By creating a type that conforms to ViewModifier, you can modify the body of any view by applying other view modifiers to the body of that view. You can even add other views on top of the original one.

So, instead of adding a bunch of view modifiers that are usually used together to achieve a specific UI, you can create a custom view modifier that modifies the view to that UI.

In the next demo, you’ll use this to create a new custom view modifier for the button that changes the color of the rectangle.

See forum comments
Download course materials from Github
Previous: Demo 1 Next: Demo 2