我有一个像这样的表格 View :
当用户点击一行时,我想取消选中最后一行并检查所选行。所以我这样写了我的代码: (例如我的最后选择= 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
}
当我点击一行而不滚动时,一切正常。我意识到,当我运行代码并立即滚动表格并选择一行时。我的程序将因错误而崩溃: “ fatal error :在解包可选值时意外发现 nil”
此行显示错误:
我不知道这里出了什么问题?
最佳答案
由于您正在使用可重复使用的单元格,因此当您尝试选择不再位于屏幕中的单元格时,应用程序将崩溃,因为该单元格不再存在于内存中,请尝试以下操作:
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
),您应该在显示之前正确设置它。为此,您需要更新 TableView 的数据集以包含更改。
关于ios - 滚动表格 View 后点击选择行时如何修复崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30972392/