【问题标题】:How to change between button styles if a condition is true in SwiftUI?如果 SwiftUI 中的条件为真,如何在按钮样式之间进行更改?
【发布时间】:2021-11-24 08:17:07
【问题描述】:

我有 2 个自定义按钮样式,我想在点击按钮时更改样式。我试过这样:

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

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

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

如果我这样做:

.buttonStyle(style1())

或者

.buttonStyle(style2())

然后错误就消失了,所以它不是来自 style1() 或 style2()。

【问题讨论】:

    标签: button swiftui


    【解决方案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)
                }
            }
        }
    
    }
    

    用法;

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

    【讨论】:

      【解决方案2】:

      这是一种快速的类型检查违规...我建议改为

      Button(action: {
          self.pressed.toggle()
      })
      {
          Text("Button")
      }.buttonStyle(Your_style(condition: pressed)) // << put conditional styling inside
      

      参见Change buttonStyle Modifier based on light or dark mode in SwiftUI中的示例解决方案

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-23
        • 1970-01-01
        • 2012-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多