显示带选定行的UIPickerView

时间:2016-02-29 19:47:30

标签: ios swift uipickerview

我想弄清楚在上次选中UIPickerView后打开UIPickerView时如何显示所选行。

当我再次打开PickerView时,我希望我的<section id="example"> <div class="section-title">Bulbasaur</div> <div class="section-list"> <span>Properties</span> <ul> <li>green</li> <li>seed</li> <li>grass</li> <li>poison</li> </ul> </div> <div class="section-image"> <img src="http://cdn.bulbagarden.net/upload/2/21/001Bulbasaur.png" /> </div> </section> img { max-width: 100px; } .section-title { width: 100%; text-align: center; font-weight: bold; } .section-list, .section-image { width: 50%; float: left; } .section-image { text-align: center; } @media screen and (max-width: 400px) { .section-list, .section-image { width: 100%; } .section-image { text-align: left; } } 设置我上次选择的选定行。

Swift有什么办法吗?

4 个答案:

答案 0 :(得分:15)

您可以在NSUserDefaults中保存最后选定的行,将视图控制器的viewDidLoad中的值和拾取器的选定行检索到值数组中所选值的索引。

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

}

答案 1 :(得分:8)

UIPickerView api允许您在代码中的任何组件中选择行:

func selectRow(_ row: Int,
   inComponent component: Int,
      animated animated: Bool)

因此,如果您为选择器的组件存储了选定的索引,则在再次显示选择器之前,请为每个组件调用此方法。

答案 2 :(得分:2)

如果这是用于存储某种设置,您可能需要考虑使用像NSUserDefaults这样的持久存储。更改选择器时,保存NSUserDefaults值。然后在viewDidLoad方法中,您可以将选择器视图设置为之前保存的行。

例如,在检测到picker视图时使用这些行,pickerView已更改为将行存储在key pickerViewValue中。把它放在didSelectRow for pickerView。

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(row, forKey: "pickerViewRow")

然后,当您加载视图时,使用此选项将选择器设置为已保存的行:

let defaults = NSUserDefaults.standardUserDefaults()
if let pickerViewRow = defaults.stringForKey("pickerViewRow")
{
    pickerView.selectRow(pickerViewRow, inComponent: 0, animated: true)
}

答案 3 :(得分:2)

适用于Swift 3

 func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if(pickerView.tag==0){
        //set some global variable
    }
}