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?
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")
}
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With