tableView.cellForRowAtIndexPath returns 零,单元格太多 (swift)

tableView.cellForRowAtIndexPath returns nil with too many cells (swift)

所以我遇到了最奇怪的事情;

我正在循环 tableView 以遍历所有单元格。它在少于 5 个单元格时工作正常,但在 "unexpectedly found nil" 更多单元格时崩溃。这是代码:

    for section in 0..<tableView.numberOfSections {
      for row in 0..<tableView.numberofRowsInSection(section) {
        let indexPath = NSIndexPath(forRow: row, inSection: section)
        let cell = tableView?.cellForRowAtIndexPath(indexPath) as? MenuItemTableViewCell

        // extract cell properties

最后一行给出了错误。

有什么想法吗?

由于单元格被重复使用,只有当给定 indexPath 的单元格当前可见时,cellForRowAtIndexPath 才会为您提供单元格。它由可选值指示。如果你想防止崩溃,你应该使用 if let

if let cell = tableView?.cellForRowAtIndexPath(indexPath) as? MenuItemTableViewCell {
     // Do something with cell
}

如果您想更新单元格中的值,您的单元格应该更新数据源项目。例如,您可以为

创建委托
protocol UITableViewCellUpdateDelegate {
    func cellDidChangeValue(cell: UITableViewCell)
}

将委托添加到您的单元格并假设我们在此单元格中有一个文本字段。我们为 EditingDidChange 事件添加了 didCHangeTextFieldValue: 目标,因此每次用户在其中输入一些内容时都会调用它。当他这样做时,我们调用委托函数。

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)
    }
}

然后在 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

}

希望对您有所帮助