我认为这是一个很好的方法:
1- 使用自己的 .xib 文件创建您的自定义部分
class CustomSection: UICollectionReusableView {
override func awakeFromNib() {
super.awakeFromNib()
}
}
2- 实现 UICollectionViewDelegateFlowLayout 委托方法
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// In case its a section header (UICollectionElementKindSectionFooter for footer)
if kind == UICollectionElementKindSectionHeader {
// This will be the section number
let section = indexPath.section
if section == 3 {
let customSection = collectionView.dequeueReusableSupplementaryView(ofKind: kind,withReuseIdentifier: "CustomSection", for: indexPath) as! CustomSection
return customSection
}
else {
//TODO: Return your default section
}
}
}
3- 不要忘记使用您的 UICollectionView 注册该部分
let customSectionNib = UINib.init(nibName: "CustomSection", bundle: nil)
collectionView.register(customSectionNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CustomSection")