You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:31:08