| 항목 | TableView | CollectionView |
|---|---|---|
| 기본 구조 | 1개의 열(Column), 여러 행(Row) | 행/열 자유롭게 배치 가능 |
| 섹션당 셀 구조 | 1차원 리스트 (섹션 → 행) | 2차원 배치 가능 (섹션 → 아이템) |
| 유즈케이스 | 리스트, 채팅, 설정 화면 등 | 그리드 형태 UI (사진첩, 상품목록 등) |
| 레이아웃 커스터마이징 | 기본적으로 단순 | UICollectionViewLayout으로 자유롭게 구성 가능 |
셀 재사용은 메모리 절약과 성능 향상을 위해 스크롤 시 화면 밖으로 나간 셀을 재활용하여 사용하는 기법입니다.
// 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:)로 재사용 큐에서 꺼내 사용TableView
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100
UILabel의 numberOfLines = 0 등)Auto Layout을 기반으로 자동 계산됨CollectionView
UICollectionViewFlowLayout 혹은 UICollectionViewCompositionalLayout을 사용해 높이 조정 필요UICollectionViewDelegateFlowLayout의 sizeForItemAt을 통해 동적으로 반환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)
}
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)