如何初始化自定义tableViewCell里面的UiPickerView?

我想在tableViewCell里面创buildPickerView 。 我使我的自定义单元格符合UIPickerViewDelegateUIPickerViewDataSource协议。 我从控制器发送数据数组到单元格(我认为这不符合MVC模式,可能你也可以build议我如何解决这个问题?)。 但是当tableview调用dequeueReusableCellWithIdentifier ,细胞会调用pickerView函数。 但是,pickerView函数使用了尚未初始化的pickerData 。 我如何解决这个问题?

下面是我的单元格的代码:

 class PickerTableViewCell: UITableViewCell, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var picker: UIPickerView! @IBOutlet weak var title: UILabel! var pickerData: Array<String>! override func awakeFromNib() { self.picker.delegate = self; self.picker.dataSource = self; super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerData.count // I get fatal error here due to pickerData is nil } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerData[row] } } 

这里是单元初始化的代码:

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("picker", forIndexPath: indexPath) as! PickerTableViewCell cell.title.text = fieldModel.editFieldArray[indexPath.row].title cell.pickerData = (fieldModel.editFieldArray[indexPath.row] as! PickerEditField).pickerData return cell } 

非常感谢您的帮助!

你的问题是你有重新加载PickerView的组件,所以在你的cellForRowAtIndexPath做一个小的改变,并在设置pickerData数组之后重新加载PickerView的组件。

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("picker", forIndexPath: indexPath) as! PickerTableViewCell cell.title.text = fieldModel.editFieldArray[indexPath.row].title cell.pickerData = (fieldModel.editFieldArray[indexPath.row] as! PickerEditField).pickerData cell.picker.reloadAllComponents(); return cell } 

也在awakeFromNib初始化你的pickerData对象

 override func awakeFromNib() { self.pickerData = Array<String>() self.picker.delegate = self; self.picker.dataSource = self; super.awakeFromNib() }