Swift 4 - 在-[UICollectionView _createPreparedCellForItemAtIndexPath]中出现断言失败

6
我刚刚将我的Xcode从8升级到9,现在我注意到当我想测试我的项目时,它会崩溃。(之前,使用Xcode 8,它可以工作)
问题是我有一个UICollectionView,其中包含单元格,其内容是从互联网下载的,因此它们的数量可能会发生变化。(现在是5个)
当我想滚动时,它立即崩溃,并显示以下异常:
2017-09-30 13:31:26.881320+0200 liveExperience[1556:568711] *** Assertion failure in -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3694.4.18/UICollectionView.m:1972
2017-09-30 13:31:26.882557+0200 liveExperience[1556:568711] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'the cell returned from -collectionView:cellForItemAtIndexPath: does not have a reuseIdentifier - cells must be retrieved by calling -dequeueReusableCellWithReuseIdentifier:forIndexPath:'
*** First throw call stack:
(0x1813ffd38 0x180914528 0x1813ffc0c 0x181d8ec24 0x18b2803c8 0x18a86f344 0x18a86a02c 0x18a80d000 0x1853dd0b4 0x1853e1194 0x18534ff24 0x185376340 0x185377180 0x1813a78b8 0x1813a5270 0x1813a582c 0x1812c62d8 0x183157f84 0x18a873880 0x104a7a800 0x180dea56c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

我检查了一下,单元格标识符没问题,唯一的输出口也没问题,现在我不知道发生了什么。

我在这里附上相关代码片段:

func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 }

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return games.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "miniGameCell", for:indexPath) as! SB


    guard let imageData = games[indexPath.row].logo as Data? else {
        return UICollectionViewCell()
    }
    cell.gameImageView.image = UIImage(data: imageData)

    return cell

}

我将我的代码从Swift 3转换为Swift 4。

1个回答

14

问题出在你代码的这一部分:

guard let imageData = games[indexPath.row].logo as Data? else {
    return UICollectionViewCell()
}

如果没有标识符,您无法返回UICollectionViewCell。 您应该使用filter从数据源中删除没有有效图像数据的元素,或者仅为没有图像的游戏显示占位符图像。


谢谢,你是对的,问题就在于,我解析了一个 JSON,然后从那里获取了我的图片链接,其中一个链接失效了,这就是为什么其中一个图片数据错误的原因。现在我已经更改了它,现在它可以完美运行了。 - Dániel Grimm
如果我有多种类型的CollectionView单元格,我需要根据条件返回它们。默认情况下应该返回什么?难道不应该返回UICollectionViewCell()吗? - Linkon Sid
1
@LinkonSid 我有同样的情况。可能不是最好的处理方式,但我只是返回任何一个单元格作为默认值,因为我知道默认值永远不会被运行。 - user7804097

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接