我正在尝试重构按钮的逻辑,因此我创建了一个内部带有三元运算符的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 是否是重构的最佳方式。
不能使用的原因是它们的类型不匹配
您可以选择其中之一。一种是
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 上测试了它,它按预期工作,这取决于你的观点,它可能会或可能不会引入错误
为了避免这种错误之王,您可以使用您自己的
modifier
和自己的 Enum
。
使用这两个元素将使您能够完全控制代码。
此问题的经过验证的答案可能会对您有所帮助 - 正在报告相同的错误! ⬇️