SwiftUI ViewModifier
SwiftUI provides so called ViewModifiers. A ViewModifier is a reusable type that defines how to change or decorate a view's appearance or behavior.
In the sample code two custom ViewModifiers Heading1 and Subheading1 are used to style text elements. The modifiers make it easy to apply consistent styles to multiple view elements.
import SwiftUI
struct SampleViewModifier2View: View {
var body: some View {
VStack(spacing: 16, content: {
Text("ViewModifier")
.font(Font.largeTitle)
VStack {
Text("Heading")
.modifier(Heading1())
Text("Subheading")
.modifier(Subheading1())
Text("Subheading")
.modifier(Subheading1())
Text("Heading")
.modifier(Heading1())
Text("Subheading")
.modifier(Subheading1())
Spacer()
}
})
}
struct Heading1: ViewModifier {
func body(content: Content) -> some View {
content
.font(.largeTitle)
.foregroundColor(.green)
.frame(maxWidth: .infinity)
.padding(8)
.background(Color.green.opacity(0.1))
.clipShape(Capsule())
.overlay {
Capsule().stroke(Color.green, lineWidth: 1)
}
.padding(.horizontal, 12)
}
}
struct Subheading1: ViewModifier {
func body(content: Content) -> some View {
content
.font(.title2)
.foregroundColor(.blue)
.frame(maxWidth: .infinity)
.padding(4)
.background(Color.blue.opacity(0.1))
.clipShape(Capsule())
.overlay {
Capsule().stroke(Color.blue, lineWidth: 1)
}
.padding(.horizontal, 24)
}
}
}
#Preview {
SampleViewModifier2View()
}