Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing UIPickerView with selected row

I am trying to figure out how to show the selected row when i open UIPickerView after it has been selected last time.

When I open my PickerView again, I want my UIPickerView to set selected row which I choose at last time.

Is there any way in Swift?

like image 634
Thiha Aung Avatar asked Feb 29 '16 19:02

Thiha Aung


3 Answers

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")
}

}
like image 63
Ahmed Onawale Avatar answered Oct 07 '22 17:10

Ahmed Onawale


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.

like image 33
Vladimir Avatar answered Oct 07 '22 18:10

Vladimir


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)
}
like image 5
yesthisisjoe Avatar answered Oct 07 '22 17:10

yesthisisjoe