返回视图时保留UIPickerView行

时间:2014-11-18 02:26:00

标签: ios swift uipickerview viewwillappear

我一直在尝试在我的应用中添加一些代码,以确保先前在选择器视图中选择的行被保留,这样当用户返回到该视图时,它会显示以前选择的行。

我以为我这样做是正确的,但它似乎对我当前的代码做了什么。

这就是我所拥有的:

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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用NSUserDefaults。

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

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