Search code examples
iosswiftuitableviewuipickerview

Swift - UIPickerView crashes app without error


I have subclassed a custom UITableViewCell, and installed a UIPickerView into it. I have wired up my IBOutlet, as well as the dataSource and delegate. However, whenever the cell is to be displayed, the app crashes (without any error in the console window). Any idea what's going on? Below is the code for the custom UITableViewCell...

   import UIKit

   class OptionPickerTableViewCell: UITableViewCell, UIPickerViewDataSource, UIPickerViewDelegate {

  //  MARK: - Variables

  let height: CGFloat = 160
  var options: [String] = [String]()

  //  MARK: - IBOutlets

  @IBOutlet weak var pickerView: UIPickerView!

  //  MARK: Functions

  func setCell(options: [String]) {
    self.options = options

  }     

  //  MARK: - UIPickerViewDelegate

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

  //  MARK: - UIPickerViewDataSource

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

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

}

UPDATE:

Error codes received were:

Getting the errors: 2015-07-09 13:21:39.924 Gym Assist[12610:473411] -[NSObject numberOfComponentsInPickerView:]: unrecognized selector sent to instance 0x7fa62c828ad0 2015-07-09 13:21:39.931 Gym Assist[12610:473411] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSObject numberOfComponentsInPickerView:]: unrecognized selector sent to instance 0x7fa62c828ad0'

Solution

  • Your project is crashing because you have assign wrong delegate and data source of your PickerView.

    So remove that and add this in your awakeFromNib method in your custom cell class:

    override func awakeFromNib() {
        super.awakeFromNib()
    
        pickerView.dataSource = self
        pickerView.delegate = self
    
    }