2017-07-19 59 views
0

我在設置UIPicker的初始值時遇到問題。我有: UIPicker在我的故事板。連接到TableViewController(I具有靜態表)類作爲IBOutlet中:設置selectedRow for UIPicker的問題

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中稱爲 - 在這裏我想對的setSelected UIPicker

UIPicker開始初始化。

它看起來像我在這裏有併發問題,但不知道如何正確解決它。我真的不知道它是如何在提到的例子中起作用的。試圖把selectedRow放在viewDidLoad中 - 結果相同。

回答

0

好吧,我找到了原因:不要在晚上寫代碼。

我已經使用錯誤函數。 我用:

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

相反的:

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

,它工作正常。