LoginSignup
27
15

More than 5 years have passed since last update.

iOS 11 UITableViewでcontentOffsetを使ったスクロールが上手くいかない

Last updated at Posted at 2017-09-11

問題

いままではこのように固定の高さのCellとrow indexから計算して指定した位置へスクロールしていました。

let index: Int = 26
let rowHeight: CGFloat = 60
let offset = CGPoint(x: 0, y: rowHeight * CGFloat(index))
tableView.setContentOffset(offset, animated: true)

しかし、iOS 11からスクロール先がおかしな位置に移動するようになりました。

解決方法

原因はiOS 11でUITableViewのプロパティestimatedRowHeightのデフォルト値がUITableViewAutomaticDimensionとなった影響でした。

そこで、セルの固定高さでスクロールを調整したい場合の解決策はestimatedRowHeightを明記する。(0を指定すると自動調整を無効という意味になります。)

tableView.estimatedRowHeight = 60

もしくは、UITableViewDelegateのメソッドで高さを明記します。

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return 60
}

以上、estimatedRowHeightの指定忘れが原因で起こるiOS 11の問題でした。

27
15
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
27
15