Browse Questions
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)