Retain UIPickerView row when returning to view

107 views Asked by At

I have been trying to add some code in my app that ensures that the row that was previously selected in a picker view is retained, so that when a user returns to that view, it shows their previously selected row.

I thought I was doing this correctly, however it doesn't seem to do anything with my current code.

Here is what I have:

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    itemSelected = colours[row]
}

override func viewWillAppear(animated: Bool) {
    var colourNum = 0
    if itemSelected == "Moss" {
        colourNum = 0
    } else if itemSelected == "Ocean" {
        colourNum = 1
    } else if itemSelected == "Maroon" {
        colourNum = 2
    } else if itemSelected == "Steel" {
        colourNum = 3
    } else if itemSelected == "Iron" {
        colourNum = 4
    } else if itemSelected == "Cayenne" {
        colourNum = 5
    }
    colourPicker.selectRow(colourNum, inComponent: 0, animated: true)
}

Any ideas?

1

There are 1 answers

0
user1502383 On

You can use NSUserDefaults.

NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "selectedColour")
NSUserDefaults.standardUserDefaults().synchronize()

var returnValue: [NSNumber]? = NSUserDefaults.standardUserDefaults().objectForKey("selectedColour") as? [NSNumber]