SwiftUI如何存储Picker选择值并正确传入按钮触发函数
问题根因
Picker的selection绑定值的类型必须和ForEach遍历的元素类型完全一致,你当前遍历的0...100是Int类型,但绑定的repetitions变量是String类型,类型不匹配导致绑定完全失效,选中值无法存入变量,变量一直保持初始值,转Int失败后就会走兜底的默认值1。
修改方案
- 将
@State修饰的repetitions变量类型从String改为Int,同时给定初始默认值 - 调整
choseDirection函数的入参类型为Int,省略字符串转整数的步骤,避免可选值兜底异常
完整修改后代码
struct ContentView: View { // 修改为Int类型,给定初始值1 @State var repetitions: Int = 1 let directions : [String] = ["Left", "Right"] var body: some View { VStack { Picker("Values", selection: $repetitions) { ForEach((0...100), id: \.self) { Text("\($0)") } } Button(action: {choseDirection(reps: repetitions)}, label: { Text("Start Drill") .frame(minWidth: 0, maxWidth: 200) .padding() .foregroundColor(.white) .background( RoundedRectangle(cornerRadius: 10) .stroke(lineWidth: 2) .background(Color.blue.cornerRadius(10)) ) }) } } // 入参改为Int类型,无需转换 func choseDirection(reps: Int) { var count = 1 while count <= reps { // 执行对应逻辑 } } }
内容的提问来源于stack exchange,提问作者NRGX
相关产品推荐
相关产品推荐

