由于单元格被重用,因此仅当给定索引路径的单元格当前可见时,cellForRowAtIndexPath 才会为您提供单元格。它由可选值指示。如果你想防止崩溃,你应该使用 if let
if let cell = tableView?.cellForRowAtIndexPath(indexPath) as? MenuItemTableViewCell {
// Do something with cell
}
如果您想更新单元格中的值,您的单元格应该更新数据源项。例如,您可以为此创建委托
protocol UITableViewCellUpdateDelegate {
func cellDidChangeValue(cell: UITableViewCell)
}
将委托添加到您的单元格中,并假设该单元格中有一个文本字段。我们添加目标didCHangeTextFieldValue:
即使是编辑 DisCharge,每次用户在其中键入内容时都会调用它。当他这样做时,我们调用委托函数。
class MyCell: UITableViewCell {
@IBOutlet var textField: UITextField!
var delegate: UITableViewCellUpdateDelegate?
override func awakeFromNib() {
textField.addTarget(self, action: Selector("didCHangeTextFieldValue:"), forControlEvents: UIControlEvents.EditingChanged)
}
@IBAction func didCHangeTextFieldValue(sender: AnyObject?) {
self.delegate?.cellDidChangeValue(cell)
}
}
Then in cellForRowAtIndexPath
您添加代表
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier", forIndexPath: indexPath)
cell.delegate = self
return cell
}
最后我们实现委托方法:
func cellDidChangeValue(cell: UITableViewCell) {
guard let indexPath = self.tableView.indexPathForCell(cell) else {
return
}
/// Update data source - we have cell and its indexPath
}
希望能帮助到你