Modern Collection View [1] - Using Cell Registration API | iOS 14
CellRegistration
을 통해 커스텀 셀을 컬렉션 뷰에 등록SupplementaryRegistration
을 통해 커스텀 뷰를 컬렉션 뷰에 등록private var cellRegistration: UICollectionView.CellRegistration<CharacterCell, Character>!
private var headerRegistation: UICollectionView.SupplementaryRegistration<HeaderView>!
UICollectionView.CellRegistration
제네릭 타입 선언을 통해 해당 셀에 해당 아이템을 사전에 등록cellRegistration = .init(handler: { cell, _, item in
cell.configure(with: item)
})
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let character = sectionedStubs[indexPath.section].characters[indexPath.item]
let cell = collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: character)
return cell
}
guard let
바인딩을 통해 타입 캐스팅한 것과 달리 using
을 통해 받아올 수 있음headerRegistation = .init(elementKind: UICollectionView.elementKindSectionHeader, handler: { [weak self] header, _, indexPath in
guard let self = self else { return }
let section = self.sectionedStubs[indexPath.section]
header.configure(with: "\(section.category) \(section.characters.count)".uppercased())
})
unc collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let section = sectionedStubs[indexPath.section]
let header = collectionView.dequeueConfiguredReusableSupplementary(using: headerRegistation, for: indexPath)
header.configure(with: "\(section.category) \(section.characters.count)".uppercased())
return header
}
using
을 통해 꺼내온 뒤 곧바로 커스텀 메소드를 통해 해당 뷰를 configure하면 된다.기본적인 셀 등록보다 해당 방법은 캐스팅을 할 필요 없이 곧바로 커스텀 인스터스 메소드를 사용할 수 있다는 점이다.