我有一个带有
TextField
和 Button
的列表。
我的目标是当我切换按钮时,我想为
TextField
提供默认值。
我可以用
Text
做到这一点,但我不知道如何用TextField
做到
struct ContentView: View {
@State var isEnableBatch: Bool = false
var body: some View {
VStack {
Button {
isEnableBatch.toggle()
} label: {
Image(isEnableBatch == true ? "EAIcon-Check_rectangle" : "EAIcon-Check_Box")
}
List {
ForEach(0 ..< 10, id: \.self) { index in
let value = isEnableBatch ? "batch Enable" : "\(index)"
Text(value) // <-- I don't know how to do here if i change to textField
}
}
.listStyle(.plain)
}
.padding()
}
}
如果我更改为使用如下的文本字段
它将显示编译错误对静态方法“buildExpression”的引用没有精确匹配
struct ContentView: View {
@State var isEnableBatch: Bool = false
@State var attValue: String = ""
var body: some View {
VStack {
Button {
isEnableBatch.toggle()
} label: {
Image(isEnableBatch == true ? "EAIcon-Check_rectangle" : "EAIcon-Check_Box")
}
List {
ForEach(0 ..< 10, id: \.self) { index in
attValue = isEnableBatch ? "batch Enable" : "\(index)" <-- how to update TextField's default value ??
TextField("", text: $attValue)
}
}
.listStyle(.plain)
}
.padding()
}
}
您可以在按钮回调中更新状态变量。
在您的示例中,所有文本字段都共享相同的绑定,因此提示也将相同:
Button {
isEnableBatch.toggle()
attValue = isEnableBatch ? "batch Enable" : "."
} label: {
Image(isEnableBatch == true ? "EAIcon-Check_rectangle" : "EAIcon-Check_Box")
}
List {
ForEach(0 ..< 10, id: \.self) { index in
TextField("", text: $attValue)
}
}