【发布时间】:2020-01-03 20:36:42
【问题描述】:
我有一个正常工作的 UICollectionView。但是我正在尝试以编程方式添加节标题,但我遇到了我无法弄清楚的崩溃。
标题的我的班级:
class EmbeddedSectionHeaderCollectionReusableView: UICollectionReusableView {
weak var sectionHeaderLabel: UILabel!
}
我在 ViewDidLoad 中的头类注册
myCollection.register(EmbeddedSectionHeaderCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
节大小定义的标题实现
// header section size. needed for implementation.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width:collectionView.frame.size.width, height:30.0)
}
viewForSupplementaryElementOfKind 代码
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as? EmbeddedSectionHeaderCollectionReusableView {
print("header should be showing")
sectionHeader.sectionHeaderLabel.text = "Hello, World"
return sectionHeader
}
return UICollectionReusableView()
}
崩溃发生在 "sectionHeader.sectionHeaderLabel.text = "Hello, World"" 说 sectionHeader 为 nil。我的直觉告诉我这是因为我没有正确初始化标头类。会这样吗?
【问题讨论】:
标签: ios swift uicollectionview