SwiftUI Custom Modifiers
SwiftUI Custom Modifiers
Create reusable styling and behavior by defining your own ViewModifier types or extension helpers.
Build a reusable ViewModifier
Encapsulate styling in a custom modifier and expose it via a View extension for reuse.
import SwiftUI
struct CardStyle: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.background(.blue.opacity(0.1))
.cornerRadius(8)
}
}
extension View {
func card() -> some View { modifier(CardStyle()) }
}
struct CustomModifiersDemo: View {
var body: some View { Text("Hello").card() }
}
import SwiftUI
struct ContentView: View {
var body: some View { CustomModifiersDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
The example above shows a reusable card-style modifier using ViewModifier and View extension.