Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI – Picker is not selecting values

When I click on the option, the picker doesn’t select value.

Nothing happens.

I made sure that the tag is of the same type as the binding member but that doesn’t help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why is this happening and how can I resolve this?

Here is the minimized example:

class Item: ObservableObject{
    var value:String
    init(_ value:String){
        self.value = value
    }
}


struct ItemsView: View {
    var body: some View {
        NavigationView{
            List{
                NavigationLink("Item 1"){
                    ItemView(item: Item("1"))
                }
                NavigationLink("Item 2"){
                    ItemView(item: Item("1"))
                }
            }
            .navigationTitle("Items")
        }
    }
}


struct ItemView: View {
    @ObservedObject var item:Item
    
    var body: some View {
        Form{
            Picker("Value", selection: $item.value){
                Text("2").tag("2")
                Text("1").tag("1")
            }
        }
        .navigationTitle("Title")
    }
}

struct ContentView: View {  
    var body: some View {
            ItemsView()
    }
}


Not sure if it matters (new in SwiftUI and Swift) but I had them in four different files…

>Solution :

Bound value should be published to notify changes back into view.

So fix is

class Item: ObservableObject{
    @Published var value:String     // << here !!
    init(_ value:String){
        self.value = value
    }
}

Tested with Xcode 13.4 / iOS 15.5

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading