问题
I am trying to create PickerView
inside tableViewCell
. I made my custom cell conform UIPickerViewDelegate
and UIPickerViewDataSource
protocols. I send data array to cell from the controller (I think this doesn't conform to MVC pattern, may be you also can suggest me how to fix that?). But when tableview calls dequeueReusableCellWithIdentifier
the cell calls pickerView function. However, pickerView function uses pickerData which is not initialized yet. How do I fix that?
Below is my code for the cell:
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]
}
}
And here is the code for the cell's initialization:
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
}
Thanks a lot for any help!
回答1:
Your issue is that you have reload the components of PickerView
so make one small change in your cellForRowAtIndexPath
and just reload the components of PickerView
after setting the pickerData
Array.
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
}
Also in awakeFromNib
initialize your pickerData object
override func awakeFromNib() {
self.pickerData = Array<String>()
self.picker.delegate = self;
self.picker.dataSource = self;
super.awakeFromNib()
}
来源:https://stackoverflow.com/questions/39494594/how-to-initialize-uipickerview-inside-custom-tableviewcell