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

标签 ios swift uicollectionview

我有一个工作正常的 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/

相关文章:

Swift:选择 UICollectionViewCell(在 UITableViewCell 内)时如何使用 Segue

ios - 项目等级的正确用途是什么?

ios - 夏令时 UIDatePicker 问题

objective-c - 在 Yosemite 上与 Frank 进行的 cucumber 测试导致段错误

ios - 具有可读内容宽度的 UICollectionViewController 流布局

ios - swift 为 collectionView 正确关闭键盘

ios - swift : Share image using UIActivityViewController

ios - 我正在用 Swift 编写 iOS 应用程序。我应该使用单例吗?

swift - 如何向一个 UITextView 添加多种样式 - 就像 iOS 笔记应用程序

ios - subview 仅第一次显示