Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Picker is not selecting values

Tags:

swift

swiftui

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.

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...

like image 729
Josh Avatar asked Mar 07 '26 04:03

Josh


1 Answers

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

like image 139
Asperi Avatar answered Mar 08 '26 20:03

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!