Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

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

I have a table view like this:

enter image description here

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:

enter image description here

I don't know what wrong in here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...