Loading...

How to group different style modifiers and reuse them across multiple SwiftUI views?

question swiftui
Ram Patra Published on March 29, 2024

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:

  • CustomStyleModifier defines a custom view modifier that applies a specific style to the views it’s applied to.
  • An extension on View is created to provide a convenient customStyle() function that applies the custom modifier.
  • In ContentView and AnotherView, you can see how the custom style modifier is applied to Text and Button views, respectively, using the customStyle() function.

This approach allows you to define common styling configurations once and reuse them across different views, promoting code reusability and maintainability.

Ram Patra Published on March 29, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui April 2, 2024 How to declare an array of Views in SwiftUI?

In SwiftUI, you can declare an array of View using the standard Swift array syntax. Here’s how you can do it:

question swiftui iOS April 2, 2024 How to force an app or a view to open in landscape only mode in iOS using SwiftUI?

In SwiftUI, you can force an app to open in landscape mode by configuring the supported interface orientations in your app’s target settings. Here’s a step-by-step guide to configuring interface orientations in Xcode:

question swiftui iOS April 2, 2024 How to open a second view from first view in iOS using SwiftUI?

In SwiftUI, you can open another view (or navigate to another view) on the click of a button by utilizing navigation views and navigation links. Here’s a basic example of how to achieve this: