如果 SwiftUI 中的条件为真,如何更改按钮样式?

Sus*_*dan 16 button swiftui

我有 2 个自定义按钮样式,我想在点击按钮时更改样式。我尝试了这样的方法:

Button(action: {
    self.pressed.toggle()
})
{
    Text("Button")
}.buttonStyle(pressed ? style1() : style2())
Run Code Online (Sandbox Code Playgroud)

但它不起作用,它从它所属的 VStack 中给了我一个错误:

Unable to infer complex closure return type; add explicit type to disambiguate
Run Code Online (Sandbox Code Playgroud)

如果我做类似的事情:

.buttonStyle(style1())
Run Code Online (Sandbox Code Playgroud)

或者

.buttonStyle(style2())
Run Code Online (Sandbox Code Playgroud)

然后错误消失,因此它不是来自 style1() 或 style2()。

Ene*_*man 1

您可以创建一个有用的扩展,如下所示

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)
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

用法;

@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())
}
Run Code Online (Sandbox Code Playgroud)