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

前端 未结 2 1300
梦毁少年i
梦毁少年i 2020-12-11 11:40

I have a table view like this:

\"enter

when the user tap one row, I want unche

相关标签:
2条回答
  • 2020-12-11 12:23

    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.

    0 讨论(0)
  • 2020-12-11 12:45

    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")
    }
    
    0 讨论(0)
提交回复
热议问题