首页 > 解决方案 > 如果 SwiftUI 中的条件为真,如何在按钮样式之间进行更改?

问题描述

我有 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()。

标签: buttonswiftui

解决方案


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

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

请参阅基于 SwiftUI 中的亮或暗模式更改按钮样式修饰符中的示例解决方案


推荐阅读