Search code examples
iosswiftuipickerview

I want to save a Selected Option in a Swift UIPickerView


so I have a UIPicker view. Now I have something selected now with that I want to save that selection so that the next time I go back to that page the same option that I selected is still there. right now it just goes to the first option selected which is grams.

Thx I'm new to Swift

Here is my code

@IBOutlet weak var pickerView: UIPickerView!

var measurementTypes = ["Grams","Ounces", "Pounds"]


func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return measurementTypes.count
}


func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return measurementTypes[row]
}


// Catpure the picker view selection
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    selected = measurementTypes[row]
    // This method is triggered whenever the user makes a change to the picker selection.
    // The parameter named row and component represents what was selected.
}

Solution

  • You can simply save the selected row number in UserDefaults so that it can be accessed next time.

    // Capture the picker view selection
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selected = measurementTypes[row]
        // Save selected row integer in User Defaults
        UserDefaults.standard.set(row, forKey: "pickerViewRow")
    }
    

    Then, in override func viewDidLoad() you can retrieve this value and set the picker view:

    let row = UserDefaults.standard.integer(forKey: "pickerViewRow")
    pickerView.selectRow(row, inComponent: 0, animated: False)