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
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

Top comments (0)

🤔 Did you know?

 
✍️ Writing your own article is easy (we even support markdown).