ios - 寄存器有什么问题(_ :forCellWithReuseIdentifier:) on UICollectionView?

标签 ios swift uitableview uicollectionview uicollectionviewcell

我正在使用 UICollectionView。正如 dequeueReusableCell(withReuseIdentifier:for:) 所期望的那样,在调用此方法之前,您必须使用 register(_:forCellWithReuseIdentifier:) 方法注册一个类或 nib 文件方法,我在我的 viewDidLoad 函数中添加了一行 as

self.collectionView!.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

现在,当我使用单元格进行出队和配置时,我遇到了错误并且应用程序崩溃了。

fatal error: unexpectedly found nil while unwrapping an Optional value

这是我的DataSource 方法:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
                                                  for: indexPath) as! PhotoCollectionViewCell

    let aPhoto = photoForIndexPath(indexPath: indexPath)
    cell.backgroundColor = UIColor.white

    cell.imageView.image = aPhoto.thumbnail //this is the line causing error

    return cell
}

这是我的 PhotoCollectionViewCell

class PhotoCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView! //I double checked this IBOutlet whether it connects with Storyboard or not
}


原始问题

现在到了有趣的部分。

我在 UICollectionView 中使用了一个 prototype 单元格,并且我从 设置了一个可重用标识符>属性检查器。此外,我将 自定义类identity inspector 更改为我的 PhotoCollectionViewCell

我搜索了同样的问题,发现在使用原型(prototype)单元时,删除

self.collectionView!.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) 

代码将起作用。我试了一下,效果很好。

But I'm curious to know the reason behind this issue. I couldn't reproduce the same issue with UITableView but with UICollectionView.

不可能重复:

UICollectionView's cell registerClass in Swift是关于如何在 UICollectionView 中注册类。但我的问题并不期望如何注册。我的问题是关于 UITableView 类不正确但仅 UICollectionView 的问题。我期待这个相互冲突的问题之间的实际区别。

最佳答案

有 3 种方法来注册单元格(UITableViewUICollectionView)。

  1. 您可以注册类(class)。这意味着单元格没有 Nib 或 Storyboard。不会加载 UI,也不会连接 outlet,只会自动调用类初始化程序。

  2. 您可以注册一个UINib(即一个xib文件)。在这种情况下,从 xib 加载单元 UI 并连接 socket 。

  3. 您可以在 Storyboard中创建原型(prototype)单元。在这种情况下,单元会自动注册到特定的 UITableViewControllerUICollectionViewController。无法在任何其他 Controller 中访问该单元格。

选项不能组合。如果 Storyboard 中有单元格原型(prototype),则无需再次注册,否则会断开 Storyboard 连接。

关于ios - 寄存器有什么问题(_ :forCellWithReuseIdentifier:) on UICollectionView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44105665/

相关文章:

android - Android 5或6(或 future 版本)是否有像iOS一样内置的条形码扫描API?

swift - 基于随机着色比较两个 Sprite 颜色?

ios - 如何根据 iPhone 尺寸 swift 使 ScrollView 达到键盘高度

ios - 如何在 TableView 中保存行的重新排序?

ios - 在表格 View 编辑模式下修改重新排序控件图标

ios - 围绕 UITableView 部分插入

iOS 8 UITableView 未选中时淡出复选标记

ios - Realm 主键迁移

iphone - iOS:下载脚本并执行?

swift - 在没有物理或 SKActions 的情况下使用 SpriteKit