SwiftUI Picker not displaying Options

Viewed 903

I can't seem to find any information on this, anywhere. So I'm learning SwiftUI, and I'm trying to add a Picker to a Form, but the picker won't display the available options when tapped. I don't really know what else to tell you guys so could someone take a look and help me fix this? thanks :)

//Outside the body code
    @State var contacts: [String] = [""]
    @State var types: [Type] = [.mobile]
//Inside the body code and inside a Form{}
    Section(header: Text("Contact")){
            ForEach(0..<types.count, id: \.self) { i in
                HStack{
                    Picker(selection: $types[i], label: Text(""), content: {
                        Text("Mobile").tag(Type.mobile)
                        Text("Land Line").tag(Type.landline)
                        Text("Email").tag(Type.email)
                    }).pickerStyle(DefaultPickerStyle())
                    .frame(width: 80.0)
                    TextField("Insert Detail", text: $contacts[i])
                }
            }
            Button("Add Another") {
                types.append(.mobile)
                contacts.append("")
            }
2 Answers

I recently managed to resolve this problem.

Picker needs to be wrapped in a NavigationView before it will work in a form.

I was able to simply add a NavigationView to the top of my view and put the form inside it, and now the picker works perfectly.

var body: some View{
    NavigationView{
        Form{
            ....
            Picker()
            ....    
        }
    }
}

As mentioned in comments-:

ForEach(:content:) should only be used for constant data. Instead conform data to Identifiable or use ForEach(:id:content:) and provide an explicit id!.

If you want to update your types array, change forEach line to ForEach(0..<types.count, id:\.self), and make sure your enum values are unique in array.

Related