如何在 SwiftUI 中的 .buttonStyle() 中使用三元运算符?

问题描述 投票:0回答:2

我正在尝试重构按钮的逻辑,因此我创建了一个内部带有三元运算符的buttonStyle,但我收到两个错误:

类型“ButtonStyle”没有成员“bordered” 类型“ButtonStyle”没有成员“borderedProminent”

这是我的代码:

struct SelectButton: View {
@Binding var isSelecting: Bool
var body: some View{
    if( isSelecting){
        Button(action: {
            self.isSelecting.toggle()
        }, label: {
            Text(isSelecting ? "Selecting" : "Select")
        })
        .buttonStyle(isSelecting ? .borderedProminent : .bordered)
        .clipShape(RoundedRectangle(cornerRadius: 25))
    }
}

}

我不知道 struct 或 func -> some View 是否是重构的最佳方式。

button swiftui struct
2个回答
0
投票

不能使用的原因是它们的类型不匹配

您可以选择其中之一。一种是

BorderedProminentButtonStyle
类型,另一种是
BorderedButtonStyle

类型

下面的代码显示了如何在不将整个按钮封装在

if
中或创建另一个视图的情况下实现结果。

您创建一个

View
扩展(这样它适用于任何视图),然后您可以有条件地应用属性。

所以这是

View
扩展

extension View {
    func `if`<Content: View>(_ conditional: Bool, content: (Self) -> Content) -> TupleView<(Self?, Content?)> {
        if conditional {
            return TupleView((nil, content(self)))
        } else {
            return TupleView((self, nil))
        }
    }
}

使用方法有点简单

Button(action: {
    self.isSelecting.toggle()
}, label: {
    Text(isSelecting ? "Selecting" : "Select")
})  
    .if(!isSelecting) { $0.buttonStyle(.bordered) }
    .if(isSelecting) { $0.buttonStyle(.borderedProminent) }
    .clipShape(RoundedRectangle(cornerRadius: 25))

我不确定是否有另一种方法可以压缩它,但我在 Playground 上测试了它,它按预期工作,这取决于你的观点,它可能会或可能不会引入错误


0
投票

为了避免这种错误之王,您可以使用您自己的

modifier
和自己的
Enum
。 使用这两个元素将使您能够完全控制代码。

此问题的经过验证的答案可能会对您有所帮助 - 正在报告相同的错误! ⬇️

已回答 - SwiftUI 条件 .buttonStyle

© www.soinside.com 2019 - 2024. All rights reserved.