在滚动tableview后点击选择行时如何修复崩溃? [英] How can I fix crash when tap to select row after scrolling the tableview?

查看:200
本文介绍了在滚动tableview后点击选择行时如何修复崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的表格视图:

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

when the user tap one row, I want uncheck the last row and check the selected row. So I wrote my code like this: (for example my 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

}

当我点击一行而不滚动时,每件事情都很好。我意识到当我运行代码并立即滚动表并选择一行时。我的程序将崩溃并出现错误:
致命错误:在展开可选值时意外发现nil

every thing working fine when I tap a row without scrolling. I realize that when I run the code and scrolling the table immediately and selected the one row. My program will crash with error: "fatal error: unexpectedly found nil while unwrapping an Optional value"

此行中的错误显示:

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

I don't know what wrong in here?

推荐答案

因为你尝试使用可重复使用的单元格要选择一个不在屏幕上的单元格,应用程序将崩溃,因为内存中不再存在单元格,请尝试以下操作:

Because you are using reusable cells when you try to select a cell that is not in the screen anymore the app will crash as the cell is no long exist in memory, try this:

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 )当前不在屏幕上,则应在显示之前正确设置它。为此,您需要更新表视图的数据集以包含更改。

This code will update the check box if the cell is currently in the screen. If it is not currently on the screen when you get the cell to reused (dequeuereusablecellwithidentifier) you should set it properly before display. To do so you will need to update the data set of the table view to contain the change.

这篇关于在滚动tableview后点击选择行时如何修复崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆