Swift UICollectionView初始化失败

3,215 阅读1分钟

提示:UICollectionView must be initialized with a non-nil layout parameter

1.检查 UICollectionViewDelegateFlowLayout(注意此处不是UICollectionViewFlowLayout)和下面的方法是否成功添加。

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 200)
    }

UICollectionViewDelegateFlowLayout相关的几个方法

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    }

2.检查colletionView初始化方式

//2.1初始化
  collectionView = UICollectionView.init(frame: CGRect(x: 0, y: 0, width: kWidth_swift, height: kHeight_Swift), collectionViewLayout: layout!)
//2.2初始化
  self.collectionView = UICollectionView.init(frame: CGRect(x: 0, y: 0, width: kWidth_swift, height: kHeight_Swift), collectionViewLayout: layout!)

//后记:当天重启电脑没用,第二天重启电脑用2.1初始化方式又好了,mmp...

3.UICollectionReusableView注册失败,原因是ReuseIdentifier错误,没有和注册时保持一致

    collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: "UICollectionElementKindSectionHeader", withReuseIdentifier: "SectionHeader")

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var reusableView: UICollectionReusableView!
        if kind == UICollectionView.elementKindSectionHeader {
            reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SectionHeader", for: indexPath)
            let sectionHeader = UIButton(frame: CGRect(x: 120, y: 16, width: kWidth_swift, height: 32))
            reusableView.addSubview(sectionHeader)
            return reusableView;
        }else{
            return UICollectionReusableView();
        }
    }

'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindSectionHeader with identifier Header - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'