LoginSignup
10

More than 5 years have passed since last update.

tableview auto layoutのcellでreloadや遷移のタイミングでscrollのpositionがずれる

Posted at

言葉じゃ伝えづらいので絵にしました。(力作)

スクリーンショット 2019-02-26 3.27.46.png

こんな感じでauto layout使用した可変の、それぞれの高さがだいぶ違うcellがあったとき。
上だとAのcellは300にもなるけどBは40みたいなとき

このとき画面遷移やreloadをするとcellがずれる事案が起こりました。。(力作2)

スクリーンショット 2019-02-26 3.27.40.png

なぜこうなる

どうやらestimatedHeightで決め打ちの高さを決めてもそこからサイズが離れすぎると起こる模様。

cellの高さを持ってあげて、estimatedHeightでそれらをしっかり返してあげればOK

HogeViewController.swift

    private var cellHeightsDictionary: [IndexPath: CGFloat] = [:]

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        self.cellHeightsDictionary[indexPath] = cell.frame.size.height
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        if let height =  self.cellHeightsDictionary[indexPath] {
            return height
        }
        return UITableView.automaticDimension
    }

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