如何在滚动tableview后点击select行来修复崩溃?

我有这样的表格视图:

在这里输入图像说明

当用户点击一行时,我想取消选中最后一行并检查选中的行。 所以我这样写我的代码:(例如我的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 } 

当我点击一行而不滚动时,每件事情都很好。 我意识到,当我运行的代码和滚动表立即select了一行。 我的程序会崩溃,错误:“致命错误:意外地发现零,而解包可选值”

错误显示在这一行:

在这里输入图像说明

我不知道这里有什么错

因为当您尝试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 

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

更好的方法将存储整个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") }