[iOS]TableView Cell의 selection 관리하기

신용철·2020년 10월 20일
2

iOS_TableView

목록 보기
6/6
  • willSelectRowAt: cell이 선택되기 전에 호출되는 함수로 indexPath를 리턴하면 select되고 nil을 return하면 선택되지 않습니다. 특정 cell의 selection을 금지할 때 사용합니다.
    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        if indexPath.row == 0 {
            return nil
        }
        return indexPath
    }
  • willDeselectRowAt: cell을 선택해제하기 직전에 호출됩니다. indexPath를 리턴하면 선택을 해제하고 nil을 리턴하면 선택상태를 유지합니다.
func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
        return indexPath
    }
  • shouldHighlightRowAt: cell이 누르고 있을 때 highlight가 되게 할지 말지 결정합니다.
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
        //첫번째 cell에만 효과 미적용
        return indexPath.row != 0
    }
  • tableView(_ tableView:didHighlightRowAt indexPath:) : highlight된 후 호출

  • tableView(_ tableView:didUnhighlightRowAt indexPath: ): highlight가 사라진 후 호출

  • CustomCell class 내부에서도 설정할 수 있습니다.

class SelectionCell: UITableViewCell {
    override func awakeFromNib() {
        super.awakeFromNib()
        
        //highlight된 상태에서의 글자 color설정
        //selected되었을 때도 계속 적용됩니다.
        textLabel?.highlightedTextColor = .red
    }
    
    /*cell이 재사용될 때도 호출됩니다. 
    tableView가 가지고 있는 selected indexPath와
    cell이 표시될 indexPath를 비교하고 선택상태롤 자동으로 설정하기 때문에 
    재사용 여부와 관계없이 항상 정확한 상태를 표시합니다.*/
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        //선택상태가 바뀔 때마다 호출됩니다.
        /*selected 파라미터로 조건문을 걸어 
        didSelected 혹은 didDeseleted되었을 때 
        실행될 코드를 작성할 수 있습니다.*/
        accessoryType = selected ? .checkmark : .none
    }
    
    override func setHighlighted(_ highlighted: Bool, animated: Bool) {
        super.setHighlighted(highlighted, animated: animated)
        //highlighted 상태가 바뀔 때마다 호출됩니다.
        /*highlighted 파라미터로 조건문을 만들어
        didHighlighted 혹은 didUnhighlighted되었을 때 
        실행될 코드를 작성할 수 있습니다.*/
    }
}
profile
iOS developer

0개의 댓글