DEV Community

Samuel Owino
Samuel Owino

Posted on

4 2

SwiftUI ViewModifiers

iOS App preview

A view modifier is a modifier that you apply to a view such as Text or Label or another modifier such as chained font() or foreground() producing a different version of the original modifier.

Protocol

protocol ViewModifier
Enter fullscreen mode Exit fullscreen mode

Basic Usage

Text("Hello World!")
    .bold()
    .font(.title)
    .foregoround(.yellow)
Enter fullscreen mode Exit fullscreen mode

Creating a Custom View Modifiers

1 Create a struct that conforms to the ViewModifier Protocol

struct PrimaryTitleTextModifier: ViewModifier {}
Enter fullscreen mode Exit fullscreen mode

2 Compose properties and return them as a view

struct PrimaryTitleStyle: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.title)
            .padding()
            .overlay {
                RoundedRectangle(cornerRadius: 15)
                    .stroke(lineWidth: 6)
            }
            .foregroundColor(.black)
    }
}

struct SecondaryTitleStyle: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.title3)
            .padding()
            .overlay {
                RoundedRectangle(cornerRadius: 15)
                    .stroke(lineWidth: 6)
            }
            .foregroundColor(.gray)
    }
}
Enter fullscreen mode Exit fullscreen mode

3 Define an extension to View that itself integrates the new modifier

extension View {
    func applyPrimaryTitleStyle() -> some View {
        modifier(PrimaryTitleStyle)
    }
}
Enter fullscreen mode Exit fullscreen mode

4 Apply the property to any view like so...

Text("Tsavo National Park")
    .applyPrimaryTitleStyle()
Enter fullscreen mode Exit fullscreen mode

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay