10
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UITableViewで指定した位置までスクロールさせたいのにクラッシュした

Last updated at Posted at 2021-03-27

任意のセルまでスクロールさせたい時は、下記コードを使うと思います。

      tableView.scrollToRow(at: indexPath, at: .top, animated: false)

…が、これだと、クラッシュすることがあった!
そんな時は、ちゃんとセルが存在しているか疑ってみてください。

自分はセルが0件の場合もセクションを表示して、そのセクションまでスクロールさせたいケースがあったのですが、上記のコードだとindexPathの場所に移動させるので、セルがなかった場合にクラッシュしました。

任意のセクションまでスクロールさせることができれば良いのですが、Swiftにはそのような機能は今のところありません。

なので、indexPath部分にNSNotFoundを指定してあげれば、クラッシュせず、スクロールされます。
~~```tableView.scrollToRow(at: NSNotFound, at: .top, animated: false)

※コメントいただいたので、修正しました!下記のように指定してあげるのが適切です。

NSNotFoundを指定したindexPathを渡してあげれば、セルの行数やセクションが0個でもクラッシュせず、スクロールされます。


```swift
if tableView.numberOfSections > 0 {
    let indexPath = IndexPath(at: NSNotFound, section: 0)
    tableView.scrollToRow(at: indexPath, at: .top, animated: false)
}

section数がいくつもあり、indexを指定したい場合はindexPathを引数でとって、section: 0の部分を適宜変えてくださいね。
sectionのindexPathをindexという引数でとるとしたら、こんなコードになるかと思います。

    let indexPath = IndexPath(at: NSNotFound, section: index)
    tableView.scrollToRow(at: indexPath, at: .top, animated: false)

公式ドキュメントにもNSNotFound is a valid row index for scrolling to a section with zero rows.と書いてあるので、推奨された方法といえます。

10
4
2

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
10
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?