gpt4 book ai didi

ios - UICollectionView 中的 viewForSupplementaryElementOfKind 返回 nil 并使用 swift 使应用程序崩溃

转载 作者:行者123 更新时间:2023-11-29 05:12:04 42 4
gpt4 key购买 nike

我有一个工作正常的 UICollectionView。但是,我试图以编程方式添加节标题,但遇到了我无法弄清楚的崩溃。

我的标题类:

class EmbeddedSectionHeaderCollectionReusableView: UICollectionReusableView {

weak var sectionHeaderLabel: UILabel!

}

我在 ViewDidLoad 中注册 header 类

myCollection.register(EmbeddedSectionHeaderCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")

我的部分大小定义的 header 实现

    // 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为零。我的直觉告诉我这是因为我没有正确初始化 header 类。会是这样吗?

最佳答案

需要添加init

class EmbeddedSectionHeaderCollectionReusableView : UICollectionReusableView { 
var sectionHeaderLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
sectionHeaderLabel = UILabel(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
self.addSubview(sectionHeaderLabel)
}
}

关于ios - UICollectionView 中的 viewForSupplementaryElementOfKind 返回 nil 并使用 swift 使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59585048/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com