【问题标题】:viewForSupplementaryElementOfKind in UICollectionView returns nil and crashes app using swiftUICollectionView 中的 viewForSupplementaryElementOfKind 返回 nil 并使用 swift 使应用程序崩溃
【发布时间】: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


    【解决方案1】:

    你需要添加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) 
     }
    }
    

    【讨论】:

    • 做到了。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多