ios - 滚动表格 View 后点击选择行时如何修复崩溃?

标签 ios xcode swift uitableview

我有一个像这样的表格 View :

enter image description here

当用户点击一行时,我想取消选中最后一行并检查所选行。所以我这样写了我的代码: (例如我的最后选择= 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

}

当我点击一行而不滚动时,一切正常。我意识到,当我运行代码并立即滚动表格并选择一行时。我的程序将因错误而崩溃: “ fatal error :在解包可选值时意外发现 nil”

此行显示错误:

enter image description here

我不知道这里出了什么问题?

最佳答案

由于您正在使用可重复使用的单元格,因此当您尝试选择不再位于屏幕中的单元格时,应用程序将崩溃,因为该单元格不再存在于内存中,请尝试以下操作:

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),您应该在显示之前正确设置它。为此,您需要更新 TableView 的数据集以包含更改。

关于ios - 滚动表格 View 后点击选择行时如何修复崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30972392/

相关文章:

ios - 快速将 mp3 文件转换为 URL

iphone - 升级到iPhone SDK 3.0导致UIKit问题

ios - 如何向 UITableView 添加编程约束?

ios - 自 iOS 13 以来,UITabBar 图标未垂直对齐

ios - SKSpriteNode 子类和触摸事件

iphone - 在 iOS 中将英制转换为公制?

ios - UIWebView 中的 PDF 不显示数字签名

ios - UICollectionView : Unrecognized selector sent to instance

swift - 如何从字节数组 ([UInt8]) 中获取一个字节 (UInt8)?

ios - iPhone简单问题: How to call a method from the main-class?