表单崩溃中的 SwiftUI 动态选择器

SwiftUI Dynamic Pickers in Form crash

我是一名新手 SwiftUI 开发人员,我在创建一个视图时遇到了问题,该视图根据用户之前在该视图中的选择动态呈现不同的选择器。要查看问题,运行 模拟器中的以下代码,将 pickerOneSelection 更改为“Picker Three”,然后将其更改回“Picker Two”并尝试更改 pickerTwoSelection。该应用程序将立即崩溃;这个玩具示例的具体错误是“线程 1:EXC_BAD_ACCESS(代码=1,地址=0x8)”。欢迎任何见解!

顺便说一句,我查看了这些问题:() and (swiftUi : 2 Pickers on one screen - app crash with "Index out of range"),但如果可能的话,我想避免将我的字符串选择变量 (pickerOneSelection, pickerThreeSelection) 转换为整数,然后必须被翻译回字符串以获得与用户选择相关联的文本。如果没有索引变量就无法完成我想做的事情,如果你能帮助我理解原因,那将非常有帮助。

import SwiftUI

struct ContentView: View {
    @State var pickerOneSelection: String = "Picker Two"
    @State var pickerTwoVisible: Bool = false
    @State var pickerTwoSelection: Int = 3
    @State var pickerThreeSelection: String = "Option 1"
    
    var pickerOneOptions = ["Picker Two", "Picker Three"]
    var pickerThreeOptions = ["Option 1", "Option 2", "Option 3"]
    
    var body: some View {
        NavigationView {
            Form {
                Picker("Picker One selection", selection: $pickerOneSelection) {
                    ForEach(pickerOneOptions, id: \.self) {
                        Text([=10=])
                    }
                } // End of Picker 1
                
                if pickerOneSelection == "Picker Two" {
                    HStack {
                        Text("Picker Two selection")
                        Spacer()
                        Button(String(pickerTwoSelection)) {
                            self.pickerTwoVisible.toggle()
                        }
                    } // End of HStack
                    
                    if pickerTwoVisible {
                        Picker("Picker Two", selection: $pickerTwoSelection) {
                            ForEach(0..<32, id: \.self) {
                                Text(String([=10=]))
                            }
                        }
                        .pickerStyle(WheelPickerStyle())
                    } // End of pickerTwoVisible
                    
                } else {
                    
                    Picker("Picker Three selection", selection: $pickerThreeSelection) {
                        ForEach(pickerThreeOptions, id: \.self) {
                            Text([=10=])
                        }
                    } // End of Picker 3
                    
                }
            } // End of Form
        } // End of NavigationView
    } // End of body
} // End of ContentView

非常感谢您的帮助和专业知识!

问题的关键在于你隐藏了picker,所以最好将它的透明度设置为0

Picker("Picker Two", selection: $pickerTwoSelection) {
                            ForEach(1..<32, id: \.self) {
                                Text(String([=10=]))
                            }
                        }
                        .pickerStyle(WheelPickerStyle())
                        .opacity(pickerTwoVisible ? 1 : 0)
                        .frame(width: pickerTwoVisible ? nil : 0, height: pickerTwoVisible ? nil : 0)