SwiftUIMidOpen-ended

How do you create a custom `ViewModifier`?

Explanation & Code

Answer: A ViewModifier packages reusable view transformations into a clean, composable unit — like a custom modifier you can chain like .padding() or .foregroundColor().

Code Example:

struct CardStyle: ViewModifier {
    var color: Color = .white

    func body(content: Content) -> some View {
        content
            .padding()
            .background(color)
            .cornerRadius(12)
            .shadow(color: .black.opacity(0.1), radius: 4, x: 0, y: 2)
    }
}

// Extend View for clean call-site syntax
extension View {
    func cardStyle(color: Color = .white) -> some View {
        modifier(CardStyle(color: color))
    }
}

// Usage
Text("Hello")
    .cardStyle()

VStack { ... }
    .cardStyle(color: .blue)

Rate your understanding:

Ready to practice more SwiftUI?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.