如何在SwiftUI的List中更新TextField的默认值
问题:SwiftUI中点击按钮批量设置List内TextField的默认值
开发SwiftUI视图时,需要实现点击切换按钮为List中的TextField设置对应默认值。使用Text组件时逻辑正常,但替换为TextField后无法运行。直接给单个@State变量赋值会触发编译错误:No exact matches in reference to static method 'buildExpression',最终通过数组存储多个状态值并绑定到对应TextField的方式解决问题。
初始可运行的Text版本代码
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 ? "批量启用" : "\(index)" Text(value) // <-- 换成TextField后不知道怎么实现 } } .listStyle(.plain) } .padding() } }
替换为TextField后的错误代码
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 ? "批量启用" : "\(index)" <-- 怎么更新TextField的默认值? TextField("", text: $attValue) } } .listStyle(.plain) } .padding() } }
最终解决方案代码
struct ContentView: View { @State var isEnableBatch: Bool = false @State var attValues: [String] = ["", "" , ""] // <- 用数组存储每个TextField的状态值 var body: some View { VStack { Button { isEnableBatch.toggle() // 切换按钮时批量更新状态值 if isEnableBatch { for index in 0 ..< 3 { attValues[index] = "批量启用" } } else { for index in 0 ..< 3 { attValues[index] = "" } } } label: { Image(isEnableBatch == true ? "EAIcon-Check_rectangle" : "EAIcon-Check_Box") } List { ForEach(0 ..< 3, id: \.self) { index in TextField("", text: $attValues[index]) // <-- 绑定对应下标的状态值 } } .listStyle(.plain) } .padding() } }
效果演示

内容的提问来源于stack exchange,提问作者Alex Cheng
相关产品推荐
相关产品推荐

