当从选取器中选择“自定义”时,我试图显示一个TextField。
struct ContentView: View {
@State private var color: String = "red" {
mutating willSet {
if newValue == "custom" {
showCutomField = true
}
else {
showCutomField = false
}
}
}
@State private var customColor: String = ""
@State private var showCutomField = false
private var choices = ["red", "green", "blue", "custom"]
var body: some View {
Form {
Picker("Color", selection: $color) {
ForEach(choices, id: \.self) {
Text($0)
}
}.pickerStyle(.segmented)
if showCutomField {
TextField("Color name", text: $customColor)
}
}
}
}
在代码中更改showCustomField
的值确实可以显示和隐藏该字段,但是由于某种原因,我无法动态更改该值。
1条答案
按热度按时间r7xajy2e1#
showCustomField
可以只是一个计算属性--不需要mutating willSet
。它应该是基于color
的条件: