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.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on March 29, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui swift September 30, 2023 How to open the Settings view in a SwiftUI app on macOS 14.0 (Sonoma)?

In macOS 14.0 (Sonoma), Apple removed support for NSApp.sendAction to open the Settings view in your SwiftUI app. You now have to use SettingsLink like below:

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 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: