Component - Custom ViewModifiers
This UI component demonstrates how to create and use a custom ViewModifier in SwiftUI. A ViewModifier lets you package styling or behavior changes to reuse on multiple views easily.
This UI component demonstrates how to create and use a custom ViewModifier in SwiftUI. A ViewModifier lets you package styling or behavior changes to reuse on multiple views easily.
ContentView
└── VStack
├── Text
└── ButtonViewModifier in SwiftUI?ViewModifier named Highlight to a Text view?.modifier()..modifier(Highlight()) with parentheses to create the modifier instance.struct RedTitle: ViewModifier {
func body(content: Content) -> some View {
content
.font(.title)
.foregroundColor(.red)
}
}
What will this code display?
Text("Welcome").modifier(RedTitle())struct BlueBackground: ViewModifier {
func body(content: Content) -> some View {
content.background(Color.blue)
}
func body(content: Content) -> some View {
content.padding()
}
}body(content:) methods defined, which is not allowed.highlight is true. Which of these implementations correctly applies the border conditionally?Bool to width (CGFloat expected, type error).Color.clear with fixed width 2: invisible but expands frame (layout shift). struct ConditionalBorder: ViewModifier {
var highlight: Bool
func body(content: Content) -> some View {
content
.border(Color.green, width: highlight ? 2 : 0)
}
} uses conditional width 2/0: border only when true, no layout shift.Pass the test and this pattern moves unknown