今天用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一下,遇到同样问题的希望能有帮助到
网友评论