- 投稿日:2019-02-26T03:35:05+09:00
tableview auto layoutのcellでreloadや遷移のタイミングでscrollのpositionがずれる
言葉じゃ伝えづらいので絵にしました。(力作)
こんな感じでauto layout使用した可変の、それぞれの高さがだいぶ違うcellがあったとき。
上だとAのcellは300にもなるけどBは40みたいなときこのとき画面遷移やreloadをするとcellがずれる事案が起こりました。。(力作2)
なぜこうなる
どうやらestimatedHeightで決め打ちの高さを決めてもそこからサイズが離れすぎると起こる模様。
cellの高さを持ってあげて、estimatedHeightでそれらをしっかり返してあげればOK
HogeViewController.swiftprivate 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 }