20190226のiOSに関する記事は1件です。

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

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

スクリーンショット 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
    }

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む