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

丶灬走出姿态 提交于 2019-11-28 12:53:43

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.

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