Search
⛓️

8. [No StoryBoard] collectionView 헤더

1 : Header 타입 정의하기

import UIKit class ProfileHeader: UICollectionReusableView { // MARK: - Properties // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .gray } required init?(coder: NSCoder) { fatalError() } // MARK: - Selectors // MARK: - Helpers }
Swift
복사

2 : 컬렉션 뷰에 등록하기

collectionView.register(ProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)
Swift
복사

3 : 컬렉션뷰 메서드 작성

1 : viewForSupplementaryElementOfKind : 헤더 구성

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) return header }
Swift
복사

2 : referenceSizeForHeaderInSection : 헤더 크기 조절

UICollectionViewDelegateFlowLayout 프로토콜 채택.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: view.frame.width, height: 300) }
Swift
복사