はじめに
table viewを実装する際におまじないのように書いていた下記のコードについて、少し意味を考えてみた。
let itemArray = ["A", "B", "C"]
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
}
環境
No | 項目 | 内容 |
---|---|---|
1 | OS | Mac |
2 | Swift | 5.6.1 |
3 | Xcode | 13.4.1 |
実装
まず、実際にはこんな感じで実装する。
let itemArray = ["A", "B", "C"]
// ①テーブルに何行のリスト、何個のセルを入れるか
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArray.count
}
// ②セルの数だけこの関数が呼び出される。indexPathプロパティはUITableViewで用意されている。(delegateメソッド)
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: K.cellIdentifier, for: indexPath)
cell.textLabel?.text = itemArray[indexPath.row]
print(indexPath) //[0, 0][0, 1][0, 2]
return cell
}
①numberOfRowsInSection
tableView(_:numberOfRowsInSection:)
何行あるかを伝える。
returnした数(INT)のセルだけ、テーブルにレンダリングされる。
②cellForRowAt indexPath
tableView(_:cellForRowAt:)
再利用可能なセルをreturnする。
・tableviewには再利用するセルのクラスを記載する。(基本変えない)
・indexPathにはテーブルの行を示す座標を記載する。(配列を順番通りに表示する場合は基本変えない。)
dequeueReusableCellにセルのIDとindexPathを入れる。
indexPathはdelegateのため、UITableViewのプロパティを利用して、テーブルの座標情報を取得する。
indexPathプロパティを用いてrowの番号を取得することで、セルに入れる文字を行に合わせてレンダリングすることができる。
おわりに
さまざまなクラスやプロトコルが用意されているので、とても便利だが、なんとなくこうかなくらいの理解しかできないのが難しいです。ご指摘があれば気軽にコメントしてください。