tableView.cellForRowAtIndexPath返回nil,单元格太多(swift)

Pol*_*lis 4 tableview ios swift

所以我有最奇怪的事情;

我正在循环tableView以迭代所有单元格.它可以在少于5个细胞的情况下正常工作,但是对于更多细胞而言,"意外发现为零"会崩溃.这是代码:

    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
Run Code Online (Sandbox Code Playgroud)

最后一行是给出错误的那一行.

有什么想法吗?

Ale*_*cur 8

因为单元格是重用的,所以只有当给定indexPath的单元格当前可见时,cellForRowAtIndexPath才会为您提供单元格.它由可选值表示.如果你想防止崩溃,你应该使用if let

if let cell = tableView?.cellForRowAtIndexPath(indexPath) as? MenuItemTableViewCell {
     // Do something with cell
}
Run Code Online (Sandbox Code Playgroud)

如果要更新单元格中的值,则单元格应更新dataSource项目.例如,您可以为此创建委托

protocol UITableViewCellUpdateDelegate {
    func cellDidChangeValue(cell: UITableViewCell)
}
Run Code Online (Sandbox Code Playgroud)

将委托添加到您的单元格,并假设我们在此单元格中有一个textField.我们didCHangeTextFieldValue:为EditingDidChange事件添加了目标,因此每次用户在其中键入somethink时都会调用它.当他这样做时,我们称之为委托功能.

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在cellForRowAtIndexPath你添加委托

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier", forIndexPath: indexPath)
    cell.delegate = self

    return cell
}
Run Code Online (Sandbox Code Playgroud)

最后我们实现了委托方法:

func cellDidChangeValue(cell: UITableViewCell) {

    guard let indexPath = self.tableView.indexPathForCell(cell) else {
        return
    }

    /// Update data source - we have cell and its indexPath

}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你