In SwiftUI, you can create custom view modifiers to encapsulate common styling configurations and reuse them across different views. Here’s how you can create and reuse a custom view modifier:
import SwiftUI
// Define a custom view modifier
struct CustomStyleModifier: ViewModifier {
func body(content: Content) -> some View {
content
.foregroundColor(.blue)
.font(.headline)
.padding()
.background(Color.yellow)
.cornerRadius(10)
}
}
// Extension to provide a convenient modifier function
extension View {
func customStyle() -> some View {
self.modifier(CustomStyleModifier())
}
}
// Example usage in different views
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.customStyle() // Apply the custom style
}
}
struct AnotherView: View {
var body: some View {
Button("Tap Me") {
// Action
}
.customStyle() // Apply the custom style
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
AnotherView()
}
}
In this example:
CustomStyleModifierdefines a custom view modifier that applies a specific style to the views it’s applied to.- An extension on
Viewis created to provide a convenientcustomStyle()function that applies the custom modifier. - In
ContentViewandAnotherView, you can see how the custom style modifier is applied toTextandButtonviews, respectively, using thecustomStyle()function.
This approach allows you to define common styling configurations once and reuse them across different views, promoting code reusability and maintainability.