UITableView 사용해보자.

Eden·2024년 11월 26일

iOS

목록 보기
10/18

간단 사용법

UITableView를 사용하려면 아래 처럼...

  1. UITableView 생성 및 뷰에 추가
  2. 데이터 소스와 델리게이트 설정
  3. 셀 등록
  4. UITableViewDataSource 메서드 구현하여 데이터 제공
  5. 필요에 따라 UITableViewDelegate 메서드 구현
  6. 레이아웃 설정으로 테이블뷰의 위치와 크기 지정

1. UITableView 생성 및 추가

테이블뷰 생성

let tableView = UITableView()

뷰에 추가

view.addSubview(tableView)

2. 데이터 소스 및 델리게이트 설정

프로토콜 채택

뷰 컨트롤러가 UITableViewDataSourceUITableViewDelegate 프로토콜을 채택한다.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
        // ...
}

데이터 소스와 델리게이트 설정

tableView.dataSource = self
tableView.delegate = self

3. 셀 등록

기본 셀 등록

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CellIdentifier")

커스텀 셀 사용 시

tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")

4. UITableViewDataSource 메서드 구현

행의 수 지정

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 데이터배열.count
}

셀 구성

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath)
     cell.textLabel?.text = 데이터배열[indexPath.row]
     return cell
}

5. UITableViewDelegate 메서드 구현 (선택 사항)

셀 선택 시 동작

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 셀이 선택되었을 때의 동작
    tableView.deselectRow(at: indexPath, animated: true)
}

6. 레이아웃 설정

오토레이아웃 사용 (SnapKit)

 tableView.snp.makeConstraints { make in
     make.edges.equalToSuperview()
}

또는 프레임 사용

tableView.frame = view.bounds
profile
🌐 Frontend &&  iOS && 대학생

1개의 댓글

comment-user-thumbnail
2024년 11월 26일

같은 테이블 뷰 동지로서 코드 보는 재미가 있군여 엇! 나도 이거했는데 엇! 나두 ! 엇! 엇!

답글 달기