[UIKit] UITableView 동적Header 만들기

a.very·2022년 10월 21일
0

Swift

목록 보기
2/2

내가 보려고, 정리하면서 쓰는 동적 헤더가 있는 tableview

🔥 불꽃 이모지가 있는 곳을 집중적으로 보면됩니다

1. 테이블뷰 만들어주기

-> 헤더도 같이 스크롤 하려고 그룹 스타일을 선택

private let tableView = UITableView(frame: CGRect.zero, style: .grouped)

2. 테이블뷰 속성 설정해주기 🔥🔥

매일 넣는 delegate, datasource 뿐만아니라
1. sectionHeight 속성을 아래와 같이 지정해주고
2. 만들어둔 헤더뷰도 register 해줄게요! (UITableViewHeaderFooterView 을 이용했습니다)

tableView.delegate = self
tableView.dataSource = self
tableView.sectionHeaderHeight = UITableView.automaticDimension // 🔥🔥  1
tableView.register(PlaceInfoHeaderView.self, forHeaderFooterViewReuseIdentifier: "PlaceInfoHeaderView") // 🔥🔥  2

3. UITableViewDataSource

do it as you already know !
저는 테스트 하기 위해서 요렇게 넣어보았어요

// MARK: - UITableViewDataSource

extension NewPlaceDetailViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return reviews.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(indexPath.row)"
        return cell
    }
    
}

4. UITableViewDelegate 🔥🔥🔥🔥

요기가 바로 동적인 헤더를 위해 매우매우매우매우 중요한 파트죠! 이거때문에 이 글 씀!

4-1. 예상되는 높이를 넣어줍니다

> Asks the delegate for the estimated height of the header of a particular section. 공식문서에서도 특정섹션의 헤더의 예상높이를 넣어준다고 나와있네요! (당연하지만)

저는 대충 366 정도의 높이지만 넉넉하게 400 넣어줄게요. 예상높이니깐 그냥 아무렇게 넣어봤어요!

    func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
        return 400
    }

4-2. HeaderView 를 넣어줄게요

공식문서에서도 섹션헤더로 어떤 뷰 보여줄지 정하는 곳이라고 하네요 (당연22)

저는 아까 위에서 등록한 view 를 넣어주었습니다

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "PlaceInfoHeaderView") as? PlaceInfoHeaderView else {
            return UIView()
        }
        
        return header
    }

5. Header view에서 해야되는 일 🔥🔥🔥🔥

저의 소중한
class PlaceInfoHeaderView: UITableViewHeaderFooterView 에서 한가지 해주어야하는 일이 있습니다

바로
바로

오토레이아웃잡기 !
스냅킷을 사용해서 상하좌우를 상위뷰에 맞게 설정하여 tableview 에 잘 달라붙도록 해주었어요!

    private func createLayout() {
        self.addSubviews([placeView, reviewTitleLabel])
        contentView.backgroundColor = .red 
        contentView.snp.makeConstraints { make in //🔥🔥
            make.edges.equalToSuperview()
        }

완성!

그렇렇 요렇게 완성!

ref

https://pratheeshbennet.medium.com/uitableview-dynamic-header-height-2cf818f21a7c
https://pratheeshbennet.medium.com/generic-reusable-uitableview-uicollectionview-f4ef5388b9f4

profile
🚚chanhee-jeong.tistory.com 🚀 github.com/chaneeii/iOS-Study-Log

0개의 댓글