Home > OS >  Add modifier to all instances of view
Add modifier to all instances of view

Time:07-10

I want to use my theme color on all instances of Toggle(), is there a way to do this with an extension?

extension Toggle {
    func content() -> some View {
        self.tint(.red)
    }
}

The above is not working, is there something else I should call on the extension to modify all instances of Toggle?

CodePudding user response:

The best way to do this is to make a custom view with @ViewBuilder.

struct CustomToggle<Content: View>: View {
    var isOn: Binding<Bool>
    var label: Content

    var body: some View {
        Toggle(isOn: isOn) { label }
            .tint(.red)
    }
    
    init(isOn: Binding<Bool>, @ViewBuilder label: @escaping () -> Content) {
        self.isOn = isOn
        self.label = label()
    }
}

CodePudding user response:

If you want to create a modifier to apply to an instance of Toggle(), can do that with the help of ViewModifiers.

i.e: First create a ViewModifier:

struct TintColorModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .tint(.red)
    }
}

extension Toggle {
    func tintStyle() -> some View {
        modifier(TintColorModifier())
    }
}

Now you can use the extension this way:

struct ContentView: View {
    var body: some View {
        Toggle()
            .tintStyle() // <-- Here
    }
}
  • Related