How to apply groups of styles using ViewModifiers
SwiftUI comes with built-in modifiers such as background()
and fontWeight()
, among others. SwiftUI also gives programmers the ability to create their own custom modifiers to do something specific. Custom modifiers allow the programmer to combine multiple existing modifiers into a single modifier.
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 ViewModifiersApp
.
How to do it…
- Change the
Text
inContentView
to"Perfect"
:Text("Perfect")
- In the
ContentView.swift
file, create a struct that conforms to theViewModifier
protocol, accepts parameter of theColor
type, and applies styles to the body:struct BackgroundStyle: ViewModifier { var bgColor: Color func body(content: Content) -> some View{ ...