SwiftUI点击ForEach内按钮更新TextField值报错的解决方法
解决SwiftUI点击分类更新搜索TextField值的问题
错误原因
你遇到的Trailing closure passed to parameter of type 'FormStyleConfiguration' that does not accept a closure错误,是因为编译器解析闭包时出现歧义,无法正确识别ForEach内Button的结构。
解决方案1:修正Button写法并明确参数命名
给ForEach的闭包参数添加命名,避免编译器歧义,同时直接在Button的action中更新绑定值:
@State private var search: String = "" var body: some View { // ...其他代码 Form { // ...其他表单元素 ForEach(observed.results, id: \.id) { result in // 明确参数命名为result Button(action: { self.search = result.result // 直接更新搜索文本 }) { Text(result.result).foregroundColor(.gray) } } // ...其他表单元素 } // ...其他代码 }
解决方案2:用Text+点击手势替代Button
如果Form内使用Button仍有样式或解析问题,也可以给Text添加onTapGesture实现点击响应,这种方式更简洁且避免Button的潜在冲突:
@State private var search: String = "" var body: some View { // ...其他代码 Form { // ...其他表单元素 ForEach(observed.results, id: \.id) { result in Text(result.result) .foregroundColor(.gray) .onTapGesture { self.search = result.result } } // ...其他表单元素 } // ...其他代码 }
补充说明
你原本写的setSearch函数可以保留,但直接在点击事件中赋值search属性会更简洁,无需额外封装函数。
内容的提问来源于stack exchange,提问作者Casey
相关产品推荐
相关产品推荐

