6월 16일 (목)

apwierk·2022년 6월 16일
0

TIL

목록 보기
20/33

TIL (Today I Learned)

6월 16일 (목)

학습 내용

cell 재사용

  • dequeueReusableCell

    code

override func tableView(_ tableView: UITableView,
                            cellForRowAt indexPath: IndexPath) -> UITableViewCell {
	let cell = tableView.dequeueReusableCell(withIdentifier: "basicStyleCell", for: indexPath)
	tableView.rowHeight = 200
	cell.textLabel!.text = "\(indexPath.section), \(indexPath.row)"
	if indexPath.row == 0 {
		cell.backgroundColor = .red
	}
	return cell
}
indexPath.row == 0 일 때, cell.backgroundColor = .red 일 경우 스크롤이 움직이면서 cell이 재사용되며 재사용되는 cell의 배경색이 .red로 변경된다. 그래서 else의 경우 backgroundColor를 .white 로 설정하여 해결 해줄 수 있따.

prepareForReuse메소드 활용

else 문을 이용하여 row가 0이 아닐 경우 white로 바꿔주는 방법도 있지만
prepareForReuse를 이용하는 방법도 있다.
TableViewCell에 prepareForReuse 메서드를 사용하여 재사용되는 셀의 속성을 초기화해주면 된다.

extension TableViewCell {
    override func prepareForReuse() {
        super.prepareForReuse()
        backgroundColor = .white
    }
}
profile
iOS 꿈나무 개발자

0개의 댓글