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

北城以北 提交于 2019-11-27 07:27:45

问题


I have a table view like this:

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

}

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"

the error show in this line:

I don't know what wrong in here?


回答1:


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

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.




回答2:


Better approach will be storing whole indexPath. not only the row. Try once i think this will work. I had the same problem in one of my app.

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
}

EDIT: or you can try this.

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

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


来源:https://stackoverflow.com/questions/30972392/how-can-i-fix-crash-when-tap-to-select-row-after-scrolling-the-tableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!