How can I fix a crash on click to select a row after scrolling through a table?

I have a table view:

enter image description here

when the user clicks one line, I want to uncheck the last line and check the selected line. So I wrote my code as follows: (e.g. 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 job works fine when I press a line without scrolling. I understand that when I run the code and scroll through the table immediately and select one row. My program crashes with the error: "Fatal error: unexpectedly found zero when deploying an optional value"

The error is displayed on this line:

enter image description here

I don’t know what is wrong here?

+2
source share
2

, , , , , :

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), . , .

+4

indexPath. . , , . .

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: .

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

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

Source: https://habr.com/ru/post/1662687/


All Articles