如何更新列表中的 TextField 值

问题描述 投票:0回答:1

我有一个带有

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()
    }
}

 

ios swift listview swiftui textfield
1个回答
0
投票

您可以在按钮回调中更新状态变量。

在您的示例中,所有文本字段都共享相同的绑定,因此提示也将相同:

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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.