Home > Mobile >  SwiftUI - Picker is not selecting values
SwiftUI - Picker is not selecting values

Time:08-16

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

CodePudding user response:

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

CodePudding user response:

To fix this, just add @Published to your variable in the Item class.

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