首页 > 解决方案 > 无法创建 UICollectionReusableView 的 IBOutlet

问题描述

我面临着陌生的问题。我已经获取UICollectionReusableView了集合视图标题并将其设置在 collectionView 中。它完全可以工作,但是当我创建它IBOutletUILabelUICollectionReusableView它总是在集合视图标题方法中返回 nil viewForSupplementaryElementOfKind。InXIB文件UILabel已成功连接。

这是我的代码。注册 CollectionView 标头

collectionView.register(Header.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header")

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
      let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as! Header
headerView.lblName.text = "Hello" //crash here
return headerView

}

这里是完整的演示 https://drive.google.com/open?id=1v2lWsQstfUiWDEldVH3Ru2HeB3LGWiXZ

标签: swiftuicollectionview

解决方案


解决了!!

我正在使用XIB集合视图标题,所以我注册的方式是没有collection view XIB. 我已经改变了

collectionView.register(Header.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header")

collectionView.register(UINib(nibName: "Header", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header")

推荐阅读