티스토리 뷰
LSLP를 구현하면서 Compositional Layout에 Header를 추가해보았다.
기존의 CompositionalLayout을 구현해주는 함수에 header의 사이즈를 추가해준다.
let headerSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(100))
let header = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: headerSize,
elementKind: UICollectionView.elementKindSectionHeader,
alignment: .top)
- NSCollectionLayoutBoundarySupplementaryItem을 사용하면 컬렉션 뷰의 섹션 시작이나 끝 부분에 보조 뷰(헤더 또는 푸터)를 추가할 수 있다.
그리고 구현했던 section에 header을 추가해준다.
section.boundarySupplementaryItems = [header]
CustomHeader를 사용할 경우 Header은 UICollectionReusableView를 상속받아 구현해줘야 한다.
(구현은 collectionViewCell과 별로 다를게 없음)
그리고 collectionView구현부분에 register함수로 header를 이 클래스를 사용해 구현해준다고 알려준다.
register함수를 자세히 보면 일반적인 cell의 register함수와 파라미터 이름이 조금 다르다.
//collectionView cell
object.register(RecipesCollectionViewCell.self,
forCellWithReuseIdentifier: RecipesCollectionViewCell.identifier)
//header
object.register(RecipesReusableHeaderView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: RecipesReusableHeaderView.identifier)
그리고 RxDataSource를 구현하는 부분에 아래처럼 header를 구현하는 부분을 추가해준다.
private let datasource = RxCollectionViewSectionedReloadDataSource<PostSectionModel>(configureCell: {
dataSource, collectionView, indexPath, item in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RecipesCollectionViewCell.identifier, for: indexPath) as! RecipesCollectionViewCell
if let path = item.files.last {
cell.setImage("\(APIInfo.baseURL)/v1/\(path)")
}
cell.setCount(item.likes.count)
return cell
}) { dataSource, collectionView, kind, indexPath in
switch kind {
case UICollectionView.elementKindSectionHeader:
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: RecipesReusableHeaderView.identifier, for: indexPath) as! RecipesReusableHeaderView
return header
default:
fatalError()
}
}
처음 보고 구현할때는 시도하기까지 겁이 많이 나는 것 같다.
막상 하면 구현해왔던 방식과 많이 다르지 않다는 것을 다시 알게되었다! 겁먹지말고 시도해보자!!
'🌱 SeSac' 카테고리의 다른 글
| RxDataSources+CompositionalLayout (0) | 2024.08.08 |
|---|