tentmaking
tentmaking

Reputation: 2146

Cannot Assign UIPickerView Delegate or DataSource

For some reason I cannot assign UIPickerView's data source or delegate to my NSObject.

I have an NSObject which extends UIPickerViewDataSource and UIPickerViewDelegate

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]
    }

}

And I have a UIViewController which attempts to set the data source and delegate. It is a UIPickerView inside a UITableViewCell.

I create the object at the top:

let repeatPickerDataSource = STRepeatPicker()

and then in cellForRowAt: I attempt to set the data source and delegate.

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

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

return cell

When I run this it crashes, if I debug and attempt to print out cell.picker.delegate I get an error: Unexpectedly found nil while unwrapping an Optional value

Does anyone know how I can assign UIPickerViewDelegate and UIPickerViewDataSource to an NSObject like this?

Upvotes: 1

Views: 238

Answers (1)

tentmaking
tentmaking

Reputation: 2146

The issue was that I was not registering my cell correctly, I was registering it as

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

when it should have been this:

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

Upvotes: 0

Related Questions