UITableViewCell 상속)numberOfRowsInSectioncellForRowAtUITableView 생성 및 View에 추가delegate, dataSource 연결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)| 메서드 | 설명 |
|---|---|
numberOfSections(in:) | 섹션 개수 반환 |
tableView(_:numberOfRowsInSection:) | 각 섹션의 행 수 반환 |
tableView(_:cellForRowAt:) | 셀 반환 |
tableView(_:didSelectRowAt:) | 셀 선택 시 호출 |
tableView(_:heightForRowAt:) | 셀 높이 지정 |
tableView(_:viewForHeaderInSection:) | 커스텀 섹션 헤더 뷰 |
UITableView는 리스트 기반 UI 구현에서 가장 많이 사용되며, 효율적인 메모리 관리와 다양한 사용자 인터랙션을 지원함. 셀 재사용, Delegate/DataSource 프로토콜 이해를 바탕으로 커스터마이징을 통해 확장 가능함.