LoginSignup
0
1

More than 1 year has passed since last update.

【Swift】TableViewのnumberOfRowsInSectionとcellForRowAt indexPath

Last updated at Posted at 2022-09-17

はじめに

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の番号を取得することで、セルに入れる文字を行に合わせてレンダリングすることができる。

おわりに

さまざまなクラスやプロトコルが用意されているので、とても便利だが、なんとなくこうかなくらいの理解しかできないのが難しいです。ご指摘があれば気軽にコメントしてください。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1