Why does my UITableView “jump” when inserting or removing a row?

后端 未结 10 1194
小蘑菇
小蘑菇 2020-12-05 10:21

(Happy to accept an answer in Swift or Objective-C)

My table view has a few sections, and when a button is pressed, I want to insert a row at the end of section 0.

10条回答
  •  感情败类
    2020-12-05 10:45

    Save estimated row heights

        private var cellHeight = [Int:CGFloat]()
        override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
            cellHeight[indexPath.row] = cell.frame.self.height
        }
        override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        if let height = cellHeight[indexPath.row] {
            return height
        }
        return tableView.estimatedRowHeight
    

    Fix scroll origin Y

        let indexPath = IndexPath(row: INDEX, section: 0)
        tableView.beginUpdates()
        tableView.insertRows(at: [indexPath], with: .fade)
        tableView.endUpdates()
        tableView.setContentOffset(tableView.contentOffset, animated: false)
    

提交回复
热议问题