【发布时间】:2016-09-14 15:40:46
【问题描述】:
我正在尝试在tableViewCell 中创建PickerView。我使我的自定义单元符合UIPickerViewDelegate 和UIPickerViewDataSource 协议。我将数据数组从控制器发送到单元格(我认为这不符合 MVC 模式,也许你也可以建议我如何解决这个问题?)。但是当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
}
非常感谢您的帮助!
【问题讨论】:
-
您是否尝试过将您的 pickerData 变量设为可选,检查它,并将其设置在您的 cellForRowAtIndexPath 中,最后重新加载组件?
标签: ios swift uitableview uipickerview