class HomeController: UICollectionViewController,UICollectionViewDelegateFlowLayout{
let cellId = "cellId"
let headerId = "headerId"
let footerId = "footerId"
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = .white
collectionView.register(ContentCell.self, forCellWithReuseIdentifier: cellId) // 내용
collectionView.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerId) // 헤더
collectionView.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: footerId) // 푸터
}
register를 통해
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader
forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter
두 가지를 선언해준다.
//MARK: - header , footer
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionView.elementKindSectionHeader{
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerId, for: indexPath)
header.backgroundColor = .yellow
return header
}else{
let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: footerId, for: indexPath)
footer.backgroundColor = .green
return footer
}
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: view.frame.width, height: 80)
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: view.frame.width, height: 80)
}
viewForSupplementaryElementOfKind을 통해 kind == UICollectionView.elementKindSectionHeader
들어오는 kind에 맞는 뷰 설정을 해준다.
referenceSizeForHeaderInSection, referenceSizeForFooterInSection을 통해 사이즈를 설정해준다.
+ 섹션을 두 개로 추가했을 때 다른섹션에서 헤더와 푸터가 필요없는경우
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 1{
return .zero
}
return CGSize(width: view.frame.width, height: 50)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
if section == 1{
return .zero
}
return CGSize(width: view.frame.width, height: 50)
}
이런식으로 referenceSizeForHeaderInSection 헤더,푸터 섹션의 사이즈를 제로로 설정한다
'개발' 카테고리의 다른 글
swift] 업데이트시 마이그레이션을 위한 버전 체크 (0) | 2021.08.06 |
---|---|
swift] SPM 만들기 - UIImage에 module의 image 선언하기 (0) | 2021.08.04 |
swift] UIbutton의 UIimage 색상변경하기 (0) | 2021.08.04 |
zsh 쉘 속도 문제 해결 (0) | 2021.04.26 |
swift] 네비게이션 바 상단 (와이파이, 시간, 배터리 색상 변경하는법) (0) | 2021.03.11 |