How to change between button styles if a condition is true in SwiftUI?

Viewed 2869

I have 2 custom button styles and I want to change the style when I tap the button. I tried this way:

Button(action: {
    self.pressed.toggle()
})
{
    Text("Button")
}.buttonStyle(pressed ? style1() : style2())

But it is not working, it is giving me an error from the VStack that it belongs to:

Unable to infer complex closure return type; add explicit type to disambiguate

If I do something like:

.buttonStyle(style1())

Or

.buttonStyle(style2())

Then the error goes away, so it's not from style1() or style2().

2 Answers

You can create a useful extension like below

extension View {

    func conditionalModifier<M1: ViewModifier, M2: ViewModifier>
        (on condition: Bool, trueCase: M1, falseCase: M2) -> some View {
        Group {
            if condition {
                self.modifier(trueCase)
            } else {
                self.modifier(falseCase)
            }
        }
    }

    func conditionalModifier<M: ViewModifier>
        (on condition: Bool, trueCase: M) -> some View {
        Group {
            if condition {
                self.modifier(trueCase)
            }
        }
    }

}

Usage;

@State var condition = false
var body: some View {
    Text("conditional modifier")
       // Apply style if condition is true, otherwise do nothing
       .conditionalModifier(on: condition, trueCase: Style1())

       // Decision between 2 style
       .conditionalModifier(on: condition, trueCase: Style1(), falseCase: Style2())
}
Related