DataStource와 Delegate

Martin·2023년 2월 18일

TIL 아카이브

목록 보기
4/11

DataStource

  • 데이터를 받아 뷰를 그려주는 역할

Delegate

  • 어떤 행동에 대한 "동작"을 제시

dequeueReusableCell(withIdentifier:for:)

  • 지정된 재사용 식별자(indexPath)에 대해 재사용이 가능한 테이블 뷰 셀 객체를 반환하고 테이블뷰에 추가한다.
/// cell을 return하는 함수에서 셀을 재사용하도록 하는 코드
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "SearchTableViewCell", for: indexPath) as! SearchTableViewCell 
    return cell 
}
  • identifier : 재사용할 셀 객체를 식별하기 위한 문자열 (nil이 아니여야 함)
  • indexPath : 셀의 위치를 특정하는 식별자
  • Return Type
    • UITabelViewCell : 재사용 식별자와 연관된 개체, 항상 유효한 셀을 반환
    • dequeueReusableCell(withIdentifier:for:) 메서드는 UITableViewDataSource 역할을 하는 객체의 tableView (_: cellForeRowAt :) 메서드 내에서만 호출

prepareForReuse()

  • tableview 의 delegate가 셀을 재사용하도록 준비
  • UITableView 에 dequeueReusableCell (withIdentifier :) 메서드에서 객체가 반환되기 직전에 호출
  • tableView (_ : cellForRowAt :)에 있는 테이블 뷰의 델리게이트는 셀을 재사용 할 때 항상 모든 콘텐츠를 reset해야함
  • 샐 객체와 관련되 재사용 식별자가 없으면 호출되지 않고, 메서드 재정의를 위해서는 슈퍼 클래스의 같은 메서드를 호출해야함
/// row의 셀의 배경색을 바꿔야할 때 사용하는 코드
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "SearchTableViewCell", for: indexPath) as! SearchTableViewCell if indexPath.row == 0 {
    cell.backgroundColor = .orange
}
   return cell 
}                                         
profile
제로부터 시작하는 이세계 Swift

0개의 댓글