首页 > 解决方案 > UICollectionView 崩溃

问题描述

在此处输入图像描述我正在为 collectionView 创建一个类,并将 CollectionView 添加到 Viewcontroller 以进行如下演示

 init(){

        let collectionViewLayout = UICollectionViewFlowLayout();
        super.init(frame: CGRect.zero, collectionViewLayout: collectionViewLayout)
        self.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCellIdentifier_SampleCollectionViewCell)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }



    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 10
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellIdentifier_SampleCollectionViewCell, for: indexPath)
        cell.contentView.backgroundColor =  UIColor.brown
        return cell
    }

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: collectionView.bounds.size.width - 16, height: 120)
    }
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        minimumLineSpacingForSectionAt section: Int) -> CGFloat {

        return 8
    }

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 8, left: 8, bottom: 8, right: 8)
    }

然后我把这个collectionView带到MainView控制器并初始化并设置代表如下

open lazy var sampleeCollectionView: SampleCollectionView = { [unowned self] in
    let collectionview = SampleCollectionView()
    collectionview.translatesAutoresizingMaskIntoConstraints = false
    collectionview.dataSource = self
    collectionview.delegate = self
    return collectionview
}()

目前应用程序崩溃任何人都可以建议我们如何解决。在这里,我在我展示的 viewController 中添加了数据源和委托。如果我将其更改为 CollectionView 类,它正在工作。是否可以将其保留在初始化位置

标签: iosswift

解决方案


您正在使用情节提要,并且尚未在您的单元格中注册 Xib 或在情节提要中使用您尝试重用的标识符创建原型。

考虑到您有一个 init 方法,它可能没有被调用,所以我认为问题出在情节提要中。


推荐阅读