LoginSignup
9
8

More than 5 years have passed since last update.

UITableViewの最後のセルのIndexPathを見つける

Posted at

一番下にスクロールしたい時とか、一番下のIndexPathを見つけたい時用のextension


extension UITableView {
  var lastIndexPath: IndexPath? {
    guard let dataSource = dataSource else { return nil }
    return dataSource.lastIndexPath(in: self)
  }
}

extension UITableViewDataSource {
  func lastIndexPath(in tableView: UITableView) -> IndexPath? {
    guard let sectionCount = self.numberOfSections?(in: tableView) else { return nil }
    let lastSection = sectionCount - 1
    let rowCountOfLastSection = self.tableView(tableView, numberOfRowsInSection: lastSection)
    let lastRow = rowCountOfLastSection - 1
    return IndexPath(row: lastRow, section: lastSection)
  }
}

ViewModel側の要素数とか見るよりは、直接DataSourceに問い合わせた方が確実だし依存関係が最小で済むなぁと思ってextensionにしてみた。
(この辺の便利なUITableViewExtみたいなpodあるのかな…)

9
8
3

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
8