LoginSignup
9
9

More than 5 years have passed since last update.

【UITableView】ページング処理のため残りの cell の数を取得する

Posted at

UITableView である程度スクロールしてある程度下端に近づいたら、追加でコンテンツを取得したい、という場合があるとおもいます。いわゆるページング処理です。
そんなときにこんな extension があると簡単にイベントを捕まえることができます。

UITableView+.swift
extension UITableView {
    // 与えられたindexPathの下部のセルの数を返す
    func belowCellsCount(cellIndexPath: IndexPath) -> Int {
        // 全てのセルの数
        let allCellsCount = Array(0 ..< self.numberOfSections).reduce(0) { (sum, sectionIndex) -> Int in
            return sum + numberOfRows(inSection: sectionIndex)
        }
        // `cellIndexPath`の上部のセクションのすべてのセルの数
        let cellsInAboveSectionCount = Array(0 ..< cellIndexPath.section).reduce(0) { (sum, sectionIndex) -> Int in
            return sum + self.numberOfRows(inSection: sectionIndex)
        }
        return allCellsCount - cellsInAboveSectionCount - cellIndexPath.row
    }
}

こんな感じで使えます。

ListViewController.swift
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if tableView.belowCellsCount(cellIndexPath: indexPath) < 6 {
        // 残りのセル数が6を下回った
        // 追加のコンテンツ取得処理
        self.viewModel.fetchList()
    }
}

contentOffset を取得して contentSize を比べることでも似たようなことができますが、デバイスごとにセルのサイズが変わったりする場合に使い勝手が変わってきます。セルの数でページングする方が確実だと思います。
同じ extension を UICollectionView にも実装すると、UICollectionView でも同じことが可能です。

9
9
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
9
9