[UIKit]테이블뷰(TableView) 섹션(Section), 다중 셀, 다양한 높이의 이미지 셀 리사이징

2022. 7. 17. 03:46SWIFT/UIKit

728x90
반응형

2022.07.16 - [STUDY(스터디)/iOS] - [iOS/Swift] 테이블뷰(TableView)안에 컬렉션뷰(CollectionVeiw)

 

[iOS/Swift] 테이블뷰(TableView)안에 컬렉션뷰(CollectionVeiw)

[iOS '스타벅스' 앱 클론코딩] 기본 테이블뷰 만드는 법!! 2022.07.07 - [PROJECT/iOS [스타벅스] CloneCoding] - [iOS '스타벅스' 앱 클론코딩] -테이블뷰(TableView) Next -> subclass of : UITableViewCell..

nlestory.tistory.com

 

 

이거 후에 이제 테이블뷰에 다른 종류의 셀을 넣어볼것이다!!

테이블뷰 셀을 하나 만든다. 나는 배너를 만들예정이라 이미지뷰 하나가 들어있는 셀을 만들었다

 

 

이제 이거를 테이블뷰에 넣어주면 된다!

let tableViewCellHBNib = UINib(nibName: "TableViewCellHomeBanner", bundle: nil)
self.mainTableView.register(tableViewCellHBNib, forCellReuseIdentifier: "TableViewCellHomeBanner")

일단 테이블뷰셀 파일을 가져와서 내 테이블뷰에 등록시켜준다

//섹션의 개수
func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}

//섹션마다 테이블뷰셀의 개수
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return homeBannerTop.count
    }else {
        return 1
    }
}

일단 이부분은 아래있는 메소드만 기본적으로 있던 것이었고

위에는 섹션으로 나누어주기 위해서 추가한 메소드이다. 

배너를 추가할 섹션과 추천메뉴를 보여줄 섹션으로 나눈다. (추천메뉴는 컬렉션뷰로 개수를 1개로 취급한다)

//섹션마다 불러올 셀에 대한 내용 할당
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    switch indexPath.section {
    case 0:
        let cell = mainTableView.dequeueReusableCell(withIdentifier: "TableViewCellHomeBanner", for: indexPath) as! TableViewCellHomeBanner

        cell.imageViewBanner.image = homeBannerTop[indexPath.row].bammerImage
        cell.selectionStyle = .none

        return cell

    case 1:
        let cell = mainTableView.dequeueReusableCell(withIdentifier: "TableViewCellHomeRecommend", for: indexPath) as! TableViewCellHomeRecommend
        cell.config()

        return cell

    default:
        return UITableViewCell()
    }
}

이부분은 섹션으로 나누어 셀에 대한 내용을 할당하는 부분이다.

기존 테이블뷰 셀에 할당하는 부분이랑 똑같다.

//섹션마다 불러올 셀에 대한 높이 지정
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    switch indexPath.section {
    case 0:
        //원본이미지의 가로길이를 세로길이로 나누어 비율을 구한 후 테이블뷰의 너비에 나누어주어 높이비율을 구한다
        let widthRatio = CGFloat(homeBannerTop[indexPath.row].bammerImage.size.width/homeBannerTop[indexPath.row].bammerImage.size.height)

        return tableView.frame.width / widthRatio

    case 1:
        return 280

    default:
        return UITableView.automaticDimension
    }

}

마지막으로 이부분 ㅜ 제일 시간이 많이 들었다ㅜ

왜 인지 모르겠는 데 처음에 똑같이 했을 때는 제대로 안나오더니 지우고 다시 처음부터 했더니 잘된다 ㅜ후하후하 

배너 이미지뷰를 Scale to Fill  로 설정한 다음에 진행하면 된다.

원본이미지의 가로세로비율을 구하여 해당 디바이스에 맞게 비율을 조정하는 방식이다.

UITableView.automaticDimension 이거 사용하면 높이가 동적으로 조절된다는 데 나는 왜 안되는 지 모르겠다.

조금 더 찾아봐야겠다 

 

 

 

드디어 완성!!!

   

 

아주 뿌듯하구만!!!

728x90
반응형