내일배움캠프 33일차

임클·2025년 4월 16일

내일배움캠프

목록 보기
34/44
post-thumbnail

하루하나 알고리즘


UIKit에서 TableView vs CollectionView, 셀 재사용, 동적 셀 높이, CollectionView 레이아웃 커스터마이징


✅ TableView와 CollectionView의 차이점

항목TableViewCollectionView
기본 구조1개의 열(Column), 여러 행(Row)행/열 자유롭게 배치 가능
섹션당 셀 구조1차원 리스트 (섹션 → 행)2차원 배치 가능 (섹션 → 아이템)
유즈케이스리스트, 채팅, 설정 화면 등그리드 형태 UI (사진첩, 상품목록 등)
레이아웃 커스터마이징기본적으로 단순UICollectionViewLayout으로 자유롭게 구성 가능

🔁 셀의 재사용 (Reusability)

셀 재사용은 메모리 절약과 성능 향상을 위해 스크롤 시 화면 밖으로 나간 셀을 재활용하여 사용하는 기법입니다.

// TableView
tableView.register(MyCell.self, forCellReuseIdentifier: "MyCell")

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
    cell.configure(with: data[indexPath.row])
    return cell
}

// CollectionView
collectionView.register(MyCell.self, forCellWithReuseIdentifier: "MyCell")

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! MyCell
    cell.configure(with: data[indexPath.item])
    return cell
}
  • register(_:forCellReuseIdentifier:)로 셀 등록
  • dequeueReusableCell(withIdentifier:for:)로 재사용 큐에서 꺼내 사용

📏 동적 셀 높이 설정 (Dynamic Cell Height)

TableView

tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100
  • 오토레이아웃 기반의 셀 내부 구성 필수 (UILabelnumberOfLines = 0 등)
  • 실제 높이는 Auto Layout을 기반으로 자동 계산됨

CollectionView

  • CollectionView는 직접 UICollectionViewFlowLayout 혹은 UICollectionViewCompositionalLayout을 사용해 높이 조정 필요
  • 또는 UICollectionViewDelegateFlowLayoutsizeForItemAt을 통해 동적으로 반환
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = collectionView.bounds.width
    let height = calculateDynamicHeight(for: data[indexPath.item])
    return CGSize(width: width, height: height)
}

🎨 CollectionView 레이아웃 커스터마이징

1. Flow Layout 커스터마이징 (기본)

let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 100, height: 100)
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 10
layout.scrollDirection = .vertical

let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)

2. Delegate를 통해 셀 크기 제어

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: 100, height: dynamicHeight)
}

3. Compositional Layout (iOS 13+)

let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
    widthDimension: .fractionalWidth(0.5),
    heightDimension: .absolute(100))
)

let group = NSCollectionLayoutGroup.horizontal(
    layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                       heightDimension: .absolute(100)),
    subitems: [item]
)

let section = NSCollectionLayoutSection(group: group)
let layout = UICollectionViewCompositionalLayout(section: section)

🧠 회고

  • TableView는 간단한 리스트 UI에 적합하고, CollectionView는 복잡한 그리드나 자유로운 레이아웃에 유리하다.
  • 셀 재사용은 TableView/CollectionView 모두 성능 최적화의 핵심이다.
  • CollectionView의 Compositional Layout은 유연하고 강력한 레이아웃 커스터마이징을 가능하게 한다.
  • 동적 셀 높이는 TableView가 훨씬 쉽게 구현되며, CollectionView는 직접 계산해줘야 한다.

0개의 댓글