在UICollectionView上注册(_:forCellWithReuseIdentifier :)有什么问题?

时间:2017-05-22 06:05:12

标签: ios swift uitableview uicollectionview uicollectionviewcell

我正在使用UICollectionView。由于dequeueReusableCell(withReuseIdentifier:for:)需要 您必须在调用此方法之前使用register(_:forCellWithReuseIdentifier:)方法注册类或nib文件 ,我在{{{}中添加了一行1}} func as

viewDidLoad

现在,当我使用单元格进行出列和配置时,我收到错误和应用程序崩溃。

  

致命错误:在解包可选值时意外发现nil

这是我的 DataSource 方法:

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

这是我的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 } 中使用prototype单元格,并从属性检查器设置了 UICollectionView 。我还将自定义类身份检查器更改为我的reusable identifier

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

PhotoCollectionViewCell
来自代码的

将起作用。我试了一下它的确有效。

  

但我很想知道这个问题背后的原因。我无法使用self.collectionView!.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) 重现相同的问题,但使用UITableView

不可能重复:

这个UICollectionView's cell registerClass in Swift是关于如何在UICollectionView中注册课程的。但我的问题并不是指望 如何注册 。我的问题是关于UICollectionView类但仅使用UITableView的问题并非如此。我期待这个相互矛盾的问题之间存在实际差异。

2 个答案:

答案 0 :(得分:11)

注册一个单元格有三种方式(UITableViewUICollectionView)。

  1. 您可以注册课程。这意味着单元格没有笔尖或故事板。不会加载任何UI并且没有连接出口,只会自动调用类初始化程序。

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

  3. 您可以在故事板中创建原型单元格。在这种情况下,单元格会自动为特定UITableViewControllerUICollectionViewController注册。任何其他控制器都无法访问该单元格。

  4. 无法合并选项。如果故事板中有单元格原型,则无需再次注册,如果有,则会中断故事板连接。

答案 1 :(得分:0)

您可以使用标识符将Nib分配给Collection视图单元格,如下所示:

self.collectionView.register(UINib(nibName: "nibName", bundle: nil), forCellWithReuseIdentifier: "cell")

希望它有所帮助。