Home > Blockchain >  SwiftUI Picker with @State Variable
SwiftUI Picker with @State Variable

Time:09-28

I am trying to get a segmented picker working using a @State variable as its selection, using a Localizable variable but the picker is not setting its state based on the initial selection.


struct TestView: View {
    
    @Binding var sSelectedMode: String
    
    
    var body: some View {
        
        VStack{
            Picker(selection: $sSelectedMode, label: Text("Mode:")) {
                Text("basicMode")
                Text("detailMode")
                
            }
            .pickerStyle(SegmentedPickerStyle())
            .frame(width: 150)
        }
}

In my Localizable files, I have (for English and French)

"basicMode" = "Basic";
"detailMode" = "Detail";
and
"basicMode = "Simple";
"detailMode" = "Détail";

The bound value for sSelectedMode is "basicMode". The picker displays the proper values based on the Language Scheme but neither Text is selected or changeable. I have also tried Picker(selection: LocalizableString(sSelectedMode), label: Text("Mode:")) but didn't work.

CodePudding user response:

try this, adding a .tag(..), works for me.

struct TestView: View {
    @Binding var sSelectedMode: String
    
    var body: some View {
        VStack{
            Picker(selection: $sSelectedMode, label: Text("Mode:")) {
                Text("basicMode").tag("basicMode") // <-- here
                Text("detailMode").tag("detailMode") // <-- here
            }
            .pickerStyle(SegmentedPickerStyle())
            .frame(width: 150)
        }
    }
}
  • Related