我想将选定的选项保存在Swift UIPickerView中

时间:2018-07-28 02:45:59

标签: ios swift uipickerview

所以我有一个UIPicker视图。现在,我选择了要保存的内容,以便下次我回到该页面时,仍然可以选择与我选择的选项相同的选项。现在,它只是转到选择的第一个选项,即克。

Thx我是Swift的新手

这是我的代码

@IBOutlet weak var pickerView: UIPickerView!

var measurementTypes = ["Grams","Ounces", "Pounds"]


func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return measurementTypes.count
}


func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return measurementTypes[row]
}


// Catpure the picker view selection
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    selected = measurementTypes[row]
    // This method is triggered whenever the user makes a change to the picker selection.
    // The parameter named row and component represents what was selected.
}

1 个答案:

答案 0 :(得分:1)

您只需将所选行号保存在UserDefaults中,以便下次访问。

// Capture the picker view selection
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    selected = measurementTypes[row]
    // Save selected row integer in User Defaults
    UserDefaults.standard.set(row, forKey: "pickerViewRow")
}

然后,在override func viewDidLoad()中,您可以检索该值并设置选择器视图:

let row = UserDefaults.standard.integer(forKey: "pickerViewRow")
pickerView.selectRow(row, inComponent: 0, animated: False)