[UIKit] Netflix Clone: TableView

Junyoung Park·2022년 10월 29일
0

UIKit

목록 보기
65/142
post-thumbnail

Building Netflix App in Swift 5 and UIKit - (Xcode 13, 2021) - Episode 2 - TableView

Netflix Clone: TableView

구현 목표

  • 셀 내에 컬렉션 뷰를 가지고 있는 커스텀 테이블 뷰 구현

구현 태스크

  • 커스텀 테이블 뷰 셀
  • 커스텀 컬렉션 뷰 셀
  • 델리게이트 / 데이터 소스 함수를 통해 헤더 및 셀 표현

핵심 코드

import UIKit

class HomeTableViewCell: UITableViewCell {
    static let identifier = "HomeTableViewCell"
    private let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.register(HomeCollectionViewCell.self, forCellWithReuseIdentifier: HomeCollectionViewCell.identifier)
        return collectionView
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        collectionView.frame = contentView.bounds
    }
    
    private func setUI() {
        contentView.backgroundColor = .systemBlue
        contentView.addSubview(collectionView)
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    func configure(with model: String) {
    }
}

extension HomeTableViewCell: UICollectionViewDelegate {
    
}

extension HomeTableViewCell: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: contentView.frame.size.width / 3, height: contentView.frame.size.height)
    }
}

extension HomeTableViewCell: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeCollectionViewCell.identifier, for: indexPath) as? HomeCollectionViewCell else {
            return UICollectionViewCell()
        }
        return cell
    }
}
  • 가데이터의 개수만큼 컬렉션 뷰 셀을 로드하는 단일한 커스텀 테이블 뷰 셀

구현 화면

profile
JUST DO IT

0개의 댓글