ios – 如何在滚动tableview后点击选择行时修复崩溃?
发布时间:2020-12-15 01:46:31 所属栏目:百科 来源:网络整理
导读:我有一个像这样的表格视图: 当用户点击一行时,我想取消选中最后一行并检查所选行.所以我写了这样的代码: (例如我的lastselected = 0) func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) { var lastIndexPath:NSInde
我有一个像这样的表格视图:
当用户点击一行时,我想取消选中最后一行并检查所选行.所以我写了这样的代码: 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 } 当我点击一行而不滚动时,每件事情都很好.我意识到当我运行代码并立即滚动表并选择一行时.我的程序会因错误而崩溃: 错误显示在这一行: 我不知道这里有什么不对? 解决方法
因为当您尝试选择不在屏幕中的单元格时使用可重用单元格时,应用程序将崩溃,因为内存中不再存在单元格,请尝试以下操作:
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)当前不在屏幕上,则应在显示之前正确设置它.为此,您需要更新表视图的数据集以包含更改. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |