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

SwiftUI分段Picker无法选中选项且点击无响应问题求助

问题排查&修复方案

代码存在3处导致Picker失效的问题:

  • Picker初始化的selection参数缺少冒号分隔符
  • ForEach方法的参数列表右括号缺失,id: \.self后需补右括号
  • Picker选中绑定值为Int类型,但遍历字符串数组生成的选项默认tag为String类型,类型不匹配导致选中逻辑失效,需要给每个选项手动添加对应索引的Int类型tag

修复后完整代码

@State private var originalUnit = 0
let sourceUnits = ["meters","kilometers","feet","yards","miles"]

var body: some View {
    NavigationView {
        Form {
            Section {
                // 修复selection参数语法
                Picker("Unit", selection: $originalUnit) {
                    // 补全ForEach参数括号,遍历索引保证tag类型匹配
                    ForEach(sourceUnits.indices, id: \.self) { index in
                        Text(sourceUnits[index])
                            .tag(index)
                    }
                }
                .pickerStyle(.segmented)
            } header: {
                Text("Choose Unit")
            }
        }
        .navigationTitle("MyApp")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

如果你希望保持直接遍历字符串元素的写法,也可以使用如下等效的ForEach实现:

ForEach(sourceUnits, id: \.self) { unit in
    Text(unit)
        .tag(sourceUnits.firstIndex(of: unit) ?? 0)
}

内容的提问来源于stack exchange,提问作者Mitchell Schaff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:06:03