[iOS]TableView관련 method와 사용법

신용철·2020년 10월 19일
0

iOS_TableView

목록 보기
5/6

1. tableView(tableView: cellForRowAt indexPath:)

  • 이 method는 cell의 디자인을 결정합니다. 여기서 중요한 개념은dequeueReusableCell입니다.

  • dequeueReusable이란?

    tableview는 메모리를 효율적으로 사용하기 위해서 재사용 queue를 관리하면서 cell 생성 요청이 들어오면 queue에 저장된 cell을 return해줍니다. 만약, 요청시점에 저장된 cell이 없다면 prototype cell을 기반으로 cell을 새로 생성합니다.

  • tableView가 스크롤 될 때 매끄럽게 보여지려면(스크롤 성능에 영향을 주지 않으려면) 최대한 가볍게 구현해야 합니다. 최대 16ms안에 모든 작업을 완료하고 cell을 리턴할 수 있어야합니다.

2. tableView seperator 설정 방법

  • tableView의 기본 seperator 속성값은 viewDidLoad()등에서 separatorInset, separatorStyle, separatorColor를 통해 아래와 같이 설정할 수 있습니다.
   self.tableView.separatorInset =
    	UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        
   //.singleLineEtched Style은 더이상 사용되지 않는 옵션이고,
   //.singleLine과 .default는 같은 속성입니다.
   self.tableView.separatorStyle = .singleLine
   
   self.tableView.separatorColor = .blue
  • 위의 설정을 기본값으로 하고 cell의 index마다 seperator를 다르게 설정할 수 있습니다. 설정은 tableView(cellForRow At:)에서 합니다. 개별 cell에서는 inset만 변경가능하고 seperateStyle과 Color를 바꾸는 것이 불가능합니다.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = UItableViewCell()
        
        //inset을 바꾸는 것만 가능
   if indexPath.row == 1 {
       cell.separatorInset = 
         UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 0)
        }
   else if indexPath.row == 2 {
       cell.separatorInset = 
         UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 30)
        }
   else {
       cell.separatorInset = self.listTableView.separatorInset
        }
        
        return cell
    }

3. tableView Cell의 index를 호출하는 method

  • indexPathForRow(at: CGPoint) : 해당 CGPoint에 있는 cell의 index값을 return합니다.

  • indexPathsForRows(in: CGRect) : 해당 CGRect 안에 있는 cell 들의 index를 배열로 return합니다.

  • tableView.indexPathsForVisibleRows : 화면에 표시된 cell들의 index를 배열로 return합니다.

  • tableView.indexPathForSelectedRow : 현재 선택되어있는 cell의 index를 return합니다.

  • tableView.indexPathsForSelectedRows : tableView가 선택된 cell들의 index를 배열로 return합니다.(multiple selection이 가능할 때 사용)

4. AccessoryView 관련 method

  • AccessoryView의 기본타입은 4가지이며, 아래와 같습니다.
   cell.accessoryType = .disclosureIndicator
   cell.accessoryType = .checkmark
   cell.accessoryType = .detailButton
   cell.accessoryType = .detailDisclosureButton
  • AccessoryView는 customView를 이용하여 만들 수도 있습니다. 그러나 AccessoryView의 크기와 위치는 조정할 수 없습니다.
class AccessoryCustomViewCell: UITableViewCell {

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        let v = UIImageView(image: UIImage(named: "star"))
        accessoryView = v
    }
}
  • AccessoryView에 tap이벤트를 설정할 수 있습니다. 그러나 이 기능은 .detailButton과 .detailDisclosureButton에 제한됩니다.
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
    //여기서 tap이벤트를 구현합니다.
    //customView로 AccessoryView를 만들 경우 역시 호출되지않습니다.
}

5. tableView의 높이 설정 방법

  • self-sizing: cell 내부의 contents의 size에 따라 RowHeight가 자동으로 설정되는 것을 말합니다. self-sizing를 사용하기 위해서는 cell이 row height값을 계산할 수 있도록 cell 내부의 레이아웃이 제약조건이 확실해야합니다. 다음 명령어로 설정할 수 있습니다.
 self.tableView.rowHeight = UITableViewAutomaticDimension
 self.tableView.estimatedRowHeight = UITableViewAutomaticDimension
  • 수치적으로 row height를 설정할 수도 있습니다. viewDidLoad() 혹은 nib의 inspector에서도 설정이 가능하지만, delegate method에서 설정한 값이 우선순위가 가장 높습니다. 따라서 다른 곳에서 tableView cell의 높이를 설정했다면 그것은 무시됩니다. delegate method는 tableView가 cell의 높이를 계산하기 전에 호출됩니다.
    또한
  • estimatedHeight는 cell높이 계산을 시작하는 값입니다. 예를 들어 cell 높이를 100으로 설정하고 estimatedHeight가 0이라면 tableView는 0부터 cell 높이를 계산하지만 estimatedHeight가 90이라면 90부터 계산을 시작합니다. 즉, estimatedHeight를 설정해주는 것은 cell의 높이 계산 속도를 높여줍니다. 따라서, 함께 설정해주는 것이 좋습니다. 설정하지 않아도 기능상에 문제는 없습니다.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // 특정 index의 height값은 고정으로 주고 나머지는 자동으로 계산하기
        if indexPath.row == 0 {
            return 100
        } else {
            return UITableViewAutomaticDimension
        }
    }
    
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
     //이 method를 사용하면 scroll의 기능을 더 향상시킬 수 있음.
        if indexPath.row == 0 {
            return 100
        } else {
            return UITableViewAutomaticDimension
        }
    }
profile
iOS developer

0개의 댓글