UITableView 프로토콜 메서드 정리

이대현·2023년 9월 13일
0

iOS

목록 보기
3/9

class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var placeAddrLabel: UILabel!
    @IBOutlet weak var placeNameLabel: UILabel!
    @IBOutlet weak var placeDistance: UILabel?
}
class MapTableViewController: UIViewController {
  @IBOutlet weak var tableView: UITableView!

  override func viewDidLoad() {
          super.viewDidLoad()

          tableView.dataSource = self
          tableView.delegate = self

          tableView.reloadData()
    }
}
  • 테이블뷰의 delegatedatasource는 protocol을 통해 구현되어 있고, self를 통해서 채택하는 과정이 필요하다. 가끔 다 구현해놓고 테이블뷰가 안보인다면 이 두 프로토콜을 채택하는 코드가 빠져있는 경우가 있을수도...

아래는 위 두 프로토콜이 실제로 구현되는 방식이다.

UITableViewDataSource

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
  let marker = allMarkers[indexPath.row]
  
  cell.placeNameLabel.text = marker.placeName
  cell.placeAddrLabel.text = marker.address
  
  return cell
}
  • numberOfRowsInSection 함수는 tableView에 사용되는 cell의 숫자를 전달한다.
  • tableView는 dequeueReusableCell 함수를 사용해, 만들어놓은 cell 클래스를 사용할 수 있다.
    • withIdentifier에 해당하는 cell을 통해 tableView의 데이터를 전달한다.

DataSource가 테이블 뷰의 row에 몇 개의 cell이 들어가야하는지, 각각의 섹션에 따라서 indexPath에 따른 데이터들을 어떤 방식으로 보여줄지를 정의했다면, delegate 메서드는 사용자와의 interaction에 관련된 내용을 정의한다.

UITableViewDelegate

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
	let marker = allMarkers[indexPath.row]
        
	if let url = URL(string: marker.placeUrl ?? "") {
		let safariVC = SFSafariViewController(url: url)
			self.present(safariVC, animated: true, completion: nil)
	}
	self.tableView.reloadData()
}
  • didSelectRowAt 함수에서는 사용자가 인터렉션을 통해 가져온 indexPath에 따라 cell 항목을 식별하고 처리할 수 있다.
  • 그 밖에도 heightForRowAt 등 셀 높이 등 테이블뷰의 세부 속성 및 디자인에 관한 내용도 델리게이트를 통해 정의할 수 있다.

*삭제 기능에 대한 글 추가 예정

profile
삽질의 기록들 👨‍💻

2개의 댓글

comment-user-thumbnail
2023년 9월 14일

깔끔한 정리 잘보고 갑니다!! 아 그래서 소주 지도는 언제 출시한다고요,,?

답글 달기
comment-user-thumbnail
2023년 9월 21일

출시해주세요 ~

답글 달기