为UIPicker设置selectedRow的问题

时间:2017-07-19 22:29:04

标签: swift3 concurrency uipickerview

我在为UIPicker设置初始值时遇到问题。 我有: UIPicker在我的故事板中。连接到TableViewController(我有静态表)类作为IBOutlet:

enter image description here

class SettingsTableViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    //Variables
    let pricePerHour: Float = 0
    let defaults = UserDefaults.standard
    let currencies = ["USD", "RUR", "UAH", "BYN", "NIS"]

    //IBOutlets
    @IBOutlet weak var isTimeCafeSwitch: UISwitch!
    @IBOutlet weak var pricePerHourTextField: UITextField!
    @IBOutlet var currencyPicker: UIPickerView!

我使用this回答作为设置初始值的示例。 但我得到了NSRangeException,因为我想我在尝试完全初始化之前设置UI选择器的值。我在代码中添加了一些打印件以显示问题:

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

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    print("Picker view initialized - getting number of rows")
    return currencies.count
}

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

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    defaults.set(currencies[row], forKey: "currency")
    print(GenericStuff.currency)
}


//System functions for view
override func viewDidLoad() {
    print("View did load")
    currencyPicker.dataSource = self
    currencyPicker.delegate = self

    //To dismiss keyboard
    self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
}

override func viewWillAppear(_ animated: Bool) {
    print("View will appear")

    //Set value for currency picker
    currencyPicker.selectedRow(inComponent: currencies.index(of: GenericStuff.currency)!)
    print("Tried to set selectedRow")

    pricePerHourTextField.text = String(describing: defaults.float(forKey: "pricePerMinute"))
    isTimeCafeSwitch.isOn = defaults.bool(forKey: "isTimeCafe")
}

这是我的输出:

View did load
View will appear
Picker view initialized - getting number of rows
Picker view initialized - getting number of rows
Picker view initialized - getting number of rows
Picker view initialized - getting number of rows
2017-07-20 01:20:42.163 CafeManager[8135:265457] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 4 beyond bounds [0 .. 0]'

因此,我可以看到序列是:

调用viewDidLoad - 这里我设置了委托和数据源。

调用viewWillAppear - 这里我试图为UIPicker设置setSelected

UIPicker开始初始化。

看起来这里有并发问题,但不确定如何正确修复它。我真的很想知道它在提到的例子中是如何工作的。试图将selectedRow放入viewDidLoad - 结果相同。

1 个答案:

答案 0 :(得分:2)

好的,我找到了原因:不要在晚上编写代码。

我使用了错误的功能。 我用过:

currencyPicker.selectedRow(inComponent: currencies.index(of: GenericStuff.currency)!)

而不是:

currencyPicker.selectRow(currencies.index(of: GenericStuff.currency)!, inComponent: 0, animated: true)

它运作正常。