How to create custom view modifiers in SwiftUI

⋅ 1 min read ⋅ SwiftUI

Table of Contents

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.
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()

Read more article about SwiftUI or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
How to request users to review your app in SwiftUI

Learn how and when you should ask for a user's review.

Next
Animating number changes in SwiftUI

iOS 17 bring a new trick to animate number in SwiftUI. Let's learn how to do it.

← Home