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
でも同じことが可能です。