给定下面的代码,我希望在点击ZERO
按钮后看到选择是ZERO
,但它总是ONE
。事实上,我不需要点击按钮名称,而是在行的中间,选择仍然是ONE
。这是意外的行为,可能是一个错误。有人对此有解释和/或解决方法吗?使用iOS 14.0和Xcode 12.2
struct TestForm : View {
@State var selection = ""
var body : some View {
Form {
Text("selection: (selection)")
HStack {
Button(action: {
selection = "ZERO"
}) {
Text("ZERO")
}
Spacer()
Button(action: {
selection = "ONE"
}) {
Text("ONE")
}
}
}
}
}
使用PlainButtonStyle((。
struct ContentView: View {
@State var selection = ""
var body : some View {
Form {
Text("selection: (selection)")
HStack {
Button(action: {
selection = "ZERO"
}) {
Text("ZERO")
.foregroundColor(.blue)
}.buttonStyle(PlainButtonStyle())
Spacer()
Button(action: {
selection = "ONE"
}) {
Text("ONE")
.foregroundColor(.blue)
}.buttonStyle(PlainButtonStyle())
}
}
}
}
我将.foregroundColor(.blue)
添加到按钮文本中,因为如果将.buttonStyle(PlainButtonStyle())
添加到按钮中,则会使按钮看起来像纯文本。