Swift:UICollectionReusableView xib创建报错

时间:2022-07-23
本文章向大家介绍Swift:UICollectionReusableView xib创建报错,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

今天用Swift CollectionView写一个页面,自定了一个Header和Footer View 运行报错,因为我使用的Reusable开源库注册Header和Footer

 collectionView.register(supplementaryViewType: SubscribeHeader.self, ofKind: UICollectionView.elementKindSectionHeader)
collectionView.register(supplementaryViewType: SubscribeFooter.self, ofKind: UICollectionView.elementKindSectionFooter)

我换成原生的注册

collectionView.register(UINib(nibName: "SubscribeHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "SubscribeHeader")
collectionView.register(UINib(nibName: "SubscribeFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "SubscribeFooter")

一样的报错奇怪了

  func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let head = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, for: indexPath, viewType: SubscribeHeader.self)
            return head
        } else {
            let foot = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, for: indexPath, viewType: SubscribeFooter.self)
            return foot
        }
    }

在使用xib的时候,存在获取nil问题

导致原因:UICollectionReusableView 类型创建时,xib未自动关联

截屏2020-08-20 10.50.37.png

记得创建UICollectionReusableView关联下,Mark一下,遇到同样问题的希望能有帮助到