iOS/UIKit
[iOS] collectionView 헤더(Header) 커스텀 및 사용
유훈 | Yuhun
2022. 2. 22. 21:06
반응형
collectionView에서 cell은 등록하고 dequeueReusableCell 메서드로 불러와 사용했습니다.
하지만 Header는 비슷하지만 조금 다른 방식을 사용해 정리해 보려 합니다.
먼저 헤더는 UICollectionReusableView을 준수합니다.
cell -> UICollectionViewCell와 다름
Header -> UICollectionReusableView
이후 헤더를 커스텀하는 방식은 기존cell처럼 하시면 됩니다.
이제 헤더를 collectionView에 register하고 불러와 사용해 보겠습니다.
register
collectionView.register(
"헤더class".self,
// 이 부분으로 header임을 구분할 수 있다.
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "고윳값 설정"
)
Header 불러오고 사용하기
// 헤더를 사용하는 dataSource 메서드
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard kind == UICollectionView.elementKindSectionHeader, // 헤더일때
let header = collectionView.dequeueReusableSupplementaryView(
ofKind: kind,
withReuseIdentifier: "등록한 고윳값",
for: indexPath
) as? "class 타입캐스팅" else {return UICollectionReusableView()}
return header
}
헤더의 크기 결정
// 참고: UICollectionViewDelegateFlowLayout의 메서드
// 헤더 사이즈 설정
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: CGFloat, height: "CGFloat")
}
반응형