[TIL] 테이블뷰

Eden·2025년 6월 18일

📌 UITableView란?

  • iOS에서 리스트 형태의 데이터를 화면에 표시하기 위한 기본 UI 컴포넌트
  • 스크롤 가능한 단일 열(Column)의 행(Row)으로 구성됨
  • 다양한 스타일, 커스터마이징 가능

🧱 주요 구성 요소

🔹 UITableView

  • 실제 목록을 표현하는 View
  • iOS에서는 UITableViewController 또는 UIViewController 내에 직접 추가 가능

🔹 UITableViewCell

  • 각 행(Row)에 해당하는 셀
  • 기본 제공 타입 외에도 커스텀 셀 정의 가능 (UITableViewCell 상속)

🔹 DataSource

  • 테이블에 표시할 데이터 제공
  • 필수 구현 메서드:
    • numberOfRowsInSection
    • cellForRowAt

🔹 Delegate

  • 셀 선택, 편집, 높이 등 사용자 상호작용 처리

🧩 기본 구현 흐름

  1. UITableView 생성 및 View에 추가
  2. delegate, dataSource 연결
  3. 필수 프로토콜 메서드 구현
  4. 셀 등록 (register) 및 재사용 (dequeueReusableCell)
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    let tableView = UITableView()
    let items = ["Apple", "Banana", "Cherry"]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.frame = view.bounds
        view.addSubview(tableView)

        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Selected: \(items[indexPath.row])")
    }
}

🎨 커스터마이징

  • 셀 클래스 커스터마이징
  • 이미지/서브뷰 추가
  • 동적 셀 높이 설정 (UITableView.automaticDimension)
  • 헤더/푸터 설정
  • 섹션 분리 (numberOfSections, titleForHeaderInSection)

🧪 실전 팁

  • reloadData() 호출 시 전체 리로드 → 성능 주의
  • reloadRows(at:), insertRows(at:), deleteRows(at:) 등으로 부분 갱신 활용
  • 셀 재사용 시에는 상태 초기화 필수 (예: prepareForReuse)
  • 셀 클릭 시 UI 피드백, 데이터 전송, 화면 전환 등 다양하게 활용 가능

🧱 자주 쓰는 Delegate & DataSource 메서드

메서드설명
numberOfSections(in:)섹션 개수 반환
tableView(_:numberOfRowsInSection:)각 섹션의 행 수 반환
tableView(_:cellForRowAt:)셀 반환
tableView(_:didSelectRowAt:)셀 선택 시 호출
tableView(_:heightForRowAt:)셀 높이 지정
tableView(_:viewForHeaderInSection:)커스텀 섹션 헤더 뷰

✅ 결론

UITableView는 리스트 기반 UI 구현에서 가장 많이 사용되며, 효율적인 메모리 관리와 다양한 사용자 인터랙션을 지원함. 셀 재사용, Delegate/DataSource 프로토콜 이해를 바탕으로 커스터마이징을 통해 확장 가능함.

profile
iOS Dev

0개의 댓글