【问题标题】:How to use a ternary operator within .buttonStyle() in SwiftUI?如何在 SwiftUI 的 .buttonStyle() 中使用三元运算符?
【发布时间】:2023-02-04 06:16:29
【问题描述】:
我正在尝试重构按钮的逻辑,因此我创建了一个内部带有三元运算符的 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
【解决方案1】:
你不能使用它的原因是因为它们有不匹配的类型
你可以选择其中之一。一个是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 上测试了它,它按预期工作,这取决于你的看法,它可能会或可能不会引入错误