uitableviewuipickerviewswift4xcode9uipickerviewdatasource

Using UIPickerView inside UITableViewController


I'm trying to add a UIPickerView into my UITableViewController and it doesn't let me enter UIPickerViewDataSource.

I'm not able to set the dataSource for the picker view... so how will this work?

I get this error: Cannot assign value of type 'TheTableViewController' to type 'UIPickerViewDataSource?'

I've looked all over for the solution and unable to find it. Thank you!

I have this code in

// The number of columns of data
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

// The number of rows of data
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return pickerData.count
}

// The data to return for the row and component (column) that's being passed in
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerData[row]
}

and it works fine, until I add UIPickerDataSource.


Solution

  • You need to make sure you conform to the UIPickerViewDataSource and have all the required methods with the exactly correct names.

    So you need to change to these:

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }