滚动表格视图后点击 select 行时如何修复崩溃?

How can I fix crash when tap to select row after scrolling the tableview?

我的 table 观点是这样的:

当用户点击一行时,我想取消选中最后一行并选中所选行。所以我这样写我的代码: (例如我的 lastselected = 0)

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        var lastIndexPath:NSIndexPath = NSIndexPath(forRow: lastSelected, inSection: 0)
        var lastCell = self.diceFaceTable.cellForRowAtIndexPath(lastIndexPath) as! TableViewCell
        var cell = self.diceFaceTable.cellForRowAtIndexPath(indexPath) as! TableViewCell


        lastCell.checkImg.image = UIImage(named: "uncheck")

        cell.checkImg.image = UIImage(named: "check")

        lastSelected = indexPath.row

}

当我在不滚动的情况下点击一行时,一切正常。我意识到当我 运行 代码并立即滚动 table 并选择一行时。我的程序将因错误而崩溃: "fatal error: unexpectedly found nil while unwrapping an Optional value"

这一行显示的错误:

我不知道这里有什么问题?

因为当您尝试 select 不再出现在屏幕中的单元格时,您使用的是可重复使用的单元格,应用程序将崩溃,因为该单元格不再存在于内存中,试试这个:

if let lastCell = self.diceFaceTable.cellForRowAtIndexPath(lastIndexPath) as! TableViewCell{
    lastCell.checkImg.image = UIImage(named: "uncheck")
}
//update the data set from the table view with the change in the icon
//for the old and the new cell

如果单元格当前在屏幕中,此代码将更新复选框。如果在您重新使用单元格 (dequeuereusablecellwithidentifier) 时它当前不在屏幕上,您应该在显示之前正确设置它。为此,您需要更新 table 视图的数据集以包含更改。

更好的方法是存储整个 indexPath。不仅是行。尝试一次我认为这会起作用。我的一个应用程序遇到了同样的问题。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    var lastCell = self.diceFaceTable.cellForRowAtIndexPath(lastSelectedIndexPath) as! TableViewCell
    var cell = self.diceFaceTable.cellForRowAtIndexPath(indexPath) as! TableViewCell

    lastCell.checkImg.image = UIImage(named: "uncheck")
    cell.checkImg.image = UIImage(named: "check")

    lastSelectedIndexPath = indexPath
}

编辑:或者你可以试试这个。

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

    var lastCell = self.diceFaceTable.cellForRowAtIndexPath(indexPath) as! TableViewCell
    lastCell.checkImg.image = UIImage(named: "uncheck")
}