How to create custom view modifiers in SwiftUI
source link: https://sarunw.com/posts/how-to-create-custom-view-modifier-in-swiftui/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to create a custom ViewModifier
To create a custom view modifier, we define a struct that conforms to the ViewModifier
protocol.
In this case, we will create a PinkLabel
modifier, which turns the text's color into pink.
struct PinkLabel: ViewModifier {
func body(content: Content) -> some View {
// ....
}
}
ViewModifier
protocol has only one requiremented method, body()
. We return the modified version of our content from this method.
public protocol ViewModifier {
@ViewBuilder @MainActor func body(content: Self.Content) -> Self.Body
}
For our PinkLabel
modifier, we just need to set the .foregroundStyle
to Color.pink
.
struct PinkLabel: ViewModifier {
func body(content: Content) -> some View {
content
.foregroundStyle(Color.pink)
}
}
That's all we need to do to create a custom view modifier.
You can easily support sarunw.com by checking out this sponsor.
Sponsor sarunw.com and reach thousands of iOS developers.
How to use a custom ViewModifier
We can apply a custom view modifier to any view using the .modifier(_:)
method.
This will apply the PinkLabel
modifier to a text view and return a modified version.
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.modifier(PinkLabel())
}
}
Here is the result. The text will be in pink color.
PinkLabel modifier.
You can easily support sarunw.com by checking out this sponsor.
Sponsor sarunw.com and reach thousands of iOS developers.
Create an extension for custom ViewModifier
Using custom modifiers with the .modifier(_:)
method is quite verbose.
I usually create an extension on View
to make it easier to use custom modifiers.
extension View {
func pinkLabel() -> some View {
modifier(PinkLabel())
}
}
Then, you can use it like this, which is more concise.
Text("Hello, world!")
.pinkLabel()
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK