无法分配UIPickerView委托或数据源

时间:2019-02-27 16:34:28

标签: ios swift uipickerview uipickerviewdatasource uipickerviewdelegate

由于某种原因,我无法分配UIPickerView的数据源或委托给我的NSObject。

我有一个NSObject,它扩展了UIPickerViewDataSourceUIPickerViewDelegate

class STRepeatPicker: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {

    let options = ["One", "Two", "Three", "Four", "Five"]

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

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

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

}

我有一个UIViewController,它试图设置数据源和委托。它是UIPickerView中的UITableViewCell

我在顶部创建对象:

let repeatPickerDataSource = STRepeatPicker()

然后在cellForRowAt:中尝试设置数据源和委托。

let cell = tableView.dequeueReusableCell(withIdentifier: "pickerCell", for: indexPath) as! PickerTableViewCell

cell.picker.delegate? = repeatPickerDataSource
cell.picker.dataSource? = repeatPickerDataSource

return cell

运行此命令时,它会崩溃,如果我调试并尝试打印出cell.picker.delegate,则会收到错误消息:Unexpectedly found nil while unwrapping an Optional value

有人知道如何将UIPickerViewDelegate和UIPickerViewDataSource分配给这样的NSObject吗?

1 个答案:

答案 0 :(得分:0)

问题是我没有正确注册我的手机,我将其注册为

self.tableView.register(UIPickerViewDelegate.self, forCellReuseIdentifier: "pickerCell")

应该在什么时候出现:

self.tableView.register(UINib.init(nibName: "PickerTableViewCell", bundle: nil), forCellReuseIdentifier: "pickerCell")