【问题标题】:Swift 4 - Assertion failure in -[UICollectionView _createPreparedCellForItemAtIndexPathSwift 4 - -[UICollectionView _createPreparedCellForItemAtIndexPath 中的断言失败
【发布时间】:2018-03-12 03:52:09
【问题描述】:

我刚刚将我的 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) 

我检查了,但小区标识符是好的,唯一的出口是好的,现在我不知道发生了什么。

我在这里附加我的相关代码sn-p:

func numberOfSections(in collectionView: UICollectionView) -> Int { 返回 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。

【问题讨论】:

    标签: swift uicollectionview swift4 xcode9


    【解决方案1】:

    问题在于你的这部分代码:

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

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

    【讨论】:

    • 谢谢,你是对的,问题是,我解析了一个 JSON,我从那里得到了我的图像的链接,其中一个链接被破坏了,这就是为什么其中一个图像数据错误。现在我改变了它,它就像一个魅力。
    • 如果我有多种类型的collectionview单元格怎么办。我需要根据情况退回它们。默认返回什么?它不应该返回 UICollectionViewCell() 吗?
    • @LinkonSid 我也有同样的情况。可能不是处理它的最佳方法,但我只是将任何一个单元格返回为默认值,因为我知道默认值永远不会运行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 2012-09-17
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多