Applying groups of styles using ViewModifier
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.
Getting ready
Create a new SwiftUI project named UsingViewModifiers
.
How to do it…
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:
- Change the string in the
ContentView
view to"Perfect"
:Text("Perfect")
- In the
ContentView.swift
file, create a struct that conforms to theViewModifier
protocol, accepts a parameter of typeColor
, and applies styles to the view's body:struct BackgroundStyle: ViewModifier { var bgColor: Color func...