I have a PickerView which should save the selected pickerView but it is selecting only the default option.I have tried using user default but it didn't work.
I am using Xcode 8.
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pizzaToppings.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
pizzaTextField.text = pizzaToppings[row]
UserDefaults.standard.set(row, forKey: "pickerViewRow")
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let attrb = NSAttributedString(string: pizzaToppings[row])
return attrb
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pizzaToppings[row]
}
And In overload function I have used user default
override func viewDidLoad() {
let row = UserDefaults.standard.integer(forKey: "pickerViewRow")
pickerView.selectRow(row, inComponent: 0, animated: false)
Let's see what are you doing here. In
viewDidLoad()you find the row (saved atpickerViewRowofUserDefaults) that the first time is 0. Then you select the first - default row. If you tap a row of picker view then you set the row at UserDefaults. The problem here is that insideviewDidLoad()your UI picker view does not have elements from your data source. You can move your code ofviewDidLoadinsideviewDidAppearand it should work.