나의 발자취
TableViewCell 재사용 (dequeueReusableCell) 본문
교안
전체 row(40개) 중 18번 정도 nil을 반환하다가 그 이후부터는 재사용.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
print(cell)
if cell == nil {
// 나중에 재사용될 때 어떻게 사용된다고 파라미터로 넘기는
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
// optional chaining(?.): the most simple way for unwrapping. nil이면 뒤의 동작을 하지 않고, 아니면 함
var content = cell?.defaultContentConfiguration()
// cell? 때문에 content도 옵셔널
content?.text = "\(indexPath.section)번째 section \(indexPath.row)번째 row"
cell?.contentConfiguration = content
// 옵셔널 언래핑 - 강제해제(무조건 있음)
return cell!
}
자, 이렇게 다시 코드를 구현하면 앱이 터진다. 왜?
dequeueReusableCell(withIdentifier: "cell", for: indexPath) 을 짰는데 재활용할 셀("cell")이 없어서.
1) StoryBoard 활용해서 만들기
그래서 오른쪽 prototype cells 숫자를 1로 해주어 Prototype Cell을 만들어준다.
그리고 반드시! Table View Cell이 선택된것을 확인하고선 오른쪽 Identifier에 "cell"이라고 해주어야 맵핑이 된다.
2) 코드로 구현하기
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var content = cell.defaultContentConfiguration()
content.text = "\(indexPath.section)번째 섹션, \(indexPath.row)번째 row"
cell.contentConfiguration = content
return cell
'앱 개발 > iOS' 카테고리의 다른 글
iOS WebKit: 웹뷰 frame 크기 조절, 버튼 넣기 (1) | 2024.09.05 |
---|---|
iOS WebKit: Web <> App 통신하기 (4) | 2024.09.05 |
UITableView의Delegate Pattern (0) | 2024.09.02 |
Protocol, Delegate Pattern in UIPickerView (0) | 2024.09.02 |
UIImageView 실습: Index 활용법, 버튼 이미지 삽입, Refactor, (0) | 2024.08.30 |
Comments