1

I was using a SwiftUI Picker like this:

Picker(getTitle(),
       selection: $model.selectedRadioButton) {
  ForEach(radioModel.buttons, id: \.self) { button in
    Text(button.title).tag(button)
  }
}
.pickerStyle(MenuPickerStyle())

This part

 selection: $model.selectedRadioButton

implies that I have to have a selected radio button. This is ok after the user selects a button but when the control displays I need no selected button to be selected

So, I can create something like that in the model

private var firstValueSelected = false

@Published var selectedRadioButton:LocalButton {
  didSet{
    firstValueSelected = true
  }
}

and then when I use the control,

Picker(getTitle(),
       selection: ?????) {
  ForEach(radioModel.buttons, id: \.self) { button in
    Text(button.title).tag(button)
  }
}
.pickerStyle(MenuPickerStyle())

and replace the ????? with a logic that returns $model.selectedRadioButton if model. firstValueSelected == true and now this is my problem, what to return if firstValueSelected == false?

Duck
  • 34,902
  • 47
  • 248
  • 470
  • You need Picker with optional selection - see here an example https://stackoverflow.com/a/65924769/12299030. – Asperi Mar 16 '21 at 15:16

1 Answers1

1

You can use ObservableObject for selected item like using a model, you can put your own custom way for saving and reading selectedRadioButton in that model as well.

import SwiftUI


class Model: ObservableObject {
    
    init() {
        self.selectedRadioButton = 2  // You can put your own custom way for saving and reading this value as well!

    }

    @Published var selectedRadioButton: Int = Int() {
        
        didSet(oldValue) {

            radioButtonBools[oldValue] = false
            radioButtonBools[selectedRadioButton] = true // Also you can use selectedRadioButton to put the radio button as True
            
        }
        
    }

    
    @Published var radioModelButtons: [String] = ["Button 1", "Button 2", "Button 3", "Button 4", "Button 5"]
    @Published var radioButtonBools: [Bool] = [false , false, false, false, false] {
        
        didSet {
            
            print(radioButtonBools)
        }
    }

}

struct ContentView: View {

    @StateObject var model: Model = Model()

    var body: some View {

        VStack {

            Picker(selection: $model.selectedRadioButton, label: Text("")) {

                ForEach(model.radioModelButtons.indices, id: \.self) { index in

                    Text(model.radioModelButtons[index])

                }
 
            }

            Text("You selected: " + model.radioModelButtons[model.selectedRadioButton].description) 
            
        }
        
        
    }
    
}
ios coder
  • 1
  • 4
  • 31
  • 91