【问题标题】:App crashes when I deselect an item in a UICollectionView当我取消选择 UICollectionView 中的项目时应用程序崩溃
【发布时间】:2015-06-08 20:47:24
【问题描述】:

我正在开发 UICollectionView。当用户选择它时,我将一个图像分配给集合视图单元格,并在用户选择其他单元格时更改图像,如下代码所示

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){

    let selectedCell : CollectionCellForAlertView = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionCellForAlertView
    println("cell selected")
    selectedCell.imageView.image = UIImage(named: "someImage.png")

}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath){
    println("deselected")
    let deselectedCell : CollectionCellForAlertView = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionCellForAlertView
    deselectedCell.imageView.image = UIImage(named: "someOtherImage.png")

}

有时它可以正常工作,但有时它会崩溃,因为 'deselectedCell' 将具有 nil 值。谁能告诉我如何解决这个问题。

【问题讨论】:

    标签: swift ios8 uicollectionview uicollectionviewcell


    【解决方案1】:

    我认为这可能对你有用。我在我的应用程序中对其进行了测试,它确实有效。

         let deselectedCell = collectionView.cellForItemAtIndexPath(indexPath) as CollectionCellForAlertView
            deselectedCell.imageView.image = UIImage(named: "someOtherImage.png")
    

    【讨论】:

    • 不,它不工作。正如我所说,有时它会在其他时候崩溃。我的收藏视图中有大约 15 个项目。当我向下滚动并继续选择和取消选择时,它有时会崩溃。
    • 你能不能把你的项目上传到github,让我看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多