Showing UIPickerView with selected row

UIPickerView api allow you to select row in any component in code:

func selectRow(_ row: Int,
   inComponent component: Int,
      animated animated: Bool)

So if you stored selected indices for your picker's components just call this method for each component before you show picker again.


If this is for storing some kind of setting, you may want to look into using persistent storage like NSUserDefaults. When the picker is changed, save the NSUserDefaults value. Then in your viewDidLoad method you can set the picker view to the row you saved earlier.

For example, use these lines when you detect the picker view pickerView has changed to store the row in the key pickerViewValue. Put this in didSelectRow for pickerView.

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(row, forKey: "pickerViewRow")

Then when you load the view, use this to set the picker to the saved row:

let defaults = NSUserDefaults.standardUserDefaults()
if let pickerViewRow = defaults.stringForKey("pickerViewRow")
{
    pickerView.selectRow(pickerViewRow, inComponent: 0, animated: true)
}

You can save the last selected row in NSUserDefaults, retrieve the value in viewDidLoad of your view controller and your picker's selected row to the index of the selected value from an array of values.

class Pick: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

var picker = UIPickerView()
var selected: String {
    return NSUserDefaults.standardUserDefaults().stringForKey("selected") ?? ""
}
var data = ["One", "Two", "Three"]

override func viewDidLoad() {
    super.viewDidLoad()
    picker.delegate = self
    picker.dataSource = self
    if let row = data.indexOf(selected) {
        picker.selectRow(row, inComponent: 0, animated: false)
    }
}

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

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

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

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    NSUserDefaults.standardUserDefaults().setObject(data[row], forKey: "selected")
}

}

For Swift 3

 func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if(pickerView.tag==0){
        //set some global variable
    }
}