Thanks to visit codestin.com
Credit goes to dev.to

DEV Community

Samuel Owino
Samuel Owino

Posted on

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
Codestin Search App Codestin Search App

Basic Usage

Text("Hello World!")
    .bold()
    .font(.title)
    .foregoround(.yellow)
Codestin Search App Codestin Search App

Creating a Custom View Modifiers

1 Create a struct that conforms to the ViewModifier Protocol

struct PrimaryTitleTextModifier: ViewModifier {}
Codestin Search App Codestin Search App

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)
    }
}
Codestin Search App Codestin Search App

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

extension View {
    func applyPrimaryTitleStyle() -> some View {
        modifier(PrimaryTitleStyle)
    }
}
Codestin Search App Codestin Search App

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

Text("Tsavo National Park")
    .applyPrimaryTitleStyle()
Codestin Search App Codestin Search App

Top comments (0)