Попытка создать UICollectionView
с использованием compositionalLayout
. Это работает для ячейки представления коллекции, но когда я пытаюсь добавить заголовок, происходит сбой с ошибкой nib регистра:
Завершение приложения из-за необработанного исключения «NSInternalInconsistencyException», причина: «не удалось удалить из очереди представление вида : SectionHeaderElementKind с идентификатором headerView - необходимо зарегистрировать перо или класс для идентификатора или подключить ячейку прототипа в раскадровке '
Реализация кода для View Controller:
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(UINib(nibName: "CollectionReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView")
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cellIdentifier")
collectionView.collectionViewLayout = customLayout()
}
func customLayout() -> UICollectionViewLayout {
let size = NSCollectionLayoutSize(
widthDimension: NSCollectionLayoutDimension.fractionalWidth(1),
heightDimension: NSCollectionLayoutDimension.estimated(44)
)
let item = NSCollectionLayoutItem(layoutSize: size)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitem: item, count: 1)
let headerSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(40)
)
let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: headerSize,
elementKind: "SectionHeaderElementKind",
alignment: .top
)
let section = NSCollectionLayoutSection(group: group)
section.boundarySupplementaryItems = [sectionHeader]
let layout = UICollectionViewCompositionalLayout(section: section)
return layout
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath) as! CollectionViewCell
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerView", for: indexPath) as! CollectionReusableView
return cell
}
}
Заголовок Посмотрите, что я создал:
class CollectionReusableView: UICollectionReusableView {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
Пожалуйста, помогите, если я что-то упустил здесь.