UICollectionView崩溃

时间:2019-03-06 10:28:49

标签: ios swift

enter image description here我正在为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
}()

当前,App崩溃了,任何人都可以建议我们如何解决。在这里,我将数据源和委托添加到要显示的viewController中。如果我将其更改为CollectionView Class,它将正常工作。是否可以将其保留在初始化位置

1 个答案:

答案 0 :(得分:1)

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

考虑到您有一个init方法,可能未调用它,因此我认为问题在情节提要中。