Sobes.tech
Middle

What is ViewModifier in SwiftUI?

sobes.tech AI

Answer from AI

ViewModifier is a protocol in SwiftUI that allows you to create reusable view appearance modifiers. It defines how to change the appearance or behavior of another View.

Example of creating and using a ViewModifier:

struct CustomButtonStyle: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding() // Add padding
            .background(Color.blue) // Blue background
            .foregroundColor(.white) // White text
            .cornerRadius(10) // Rounded corners
    }
}

// Using the modifier
struct ContentView: View {
    var body: some View {
        Button("Press me") {
            // Action on press
        }
        .modifier(CustomButtonStyle()) // Apply the modifier
    }
}

Advantages of using ViewModifier:

  • Reusability: Formatting logic is extracted into a separate type that can be applied to different Views.
  • Code cleanliness: The View becomes more concise, styles are not scattered throughout the code.
  • Testability: The modifier can be tested independently.

You can create an extension for View to make using the modifier more convenient:

extension View {
    func customButton() -> some View {
        self.modifier(CustomButtonStyle())
    }
}

// Using the extension
struct ContentView: View {
    var body: some View {
        Button("Press me") {
            // Action on press
        }
        .customButton()
    }
}
What is ViewModifier in SwiftUI? — iOS - sobes.tech