Table view "jumps" when I try to scrollToRow with UITableViewAutomaticDimension. The fix also makes it jump

Viewed 603

I have the same issue as this one. I have tried to implement a suggested fix, and instead of a table view going the whole way up and then going to the last row again, I got the small jumps up. I need to make the animations smoother. Can it be done with UITableViewAutomaticDimension?

Here is a GIF showing the broken animation


My code is as below:

@objc fileprivate func addNext() {
  guard rowsCount.value < cellModels.count else { return }

  let lastIndexPath = IndexPath(row: rowsCount.value, section: 0)
  rowsCount.value += 1

  CATransaction.begin()
  CATransaction.setCompletionBlock({ () -> Void in
    self.scrollToLastMessage()
  })

  tableView.update {
    tableView.insertRows(at: [lastIndexPath], with: .none)
  }
  CATransaction.commit()
}

func scrollToLastMessage()
{
  let bottomRow = tableView.numberOfRows(inSection: 0) - 1
  let bottomMessageIndex = IndexPath(row: bottomRow, section: 0)

  guard bottomRow >= 0
    else { return }

  CATransaction.begin()
  CATransaction.setCompletionBlock({ () -> Void in

    self.tableView.scrollToRow(at: bottomMessageIndex, at: .bottom, animated: true)
  })

  let contentOffset = tableView.contentOffset.y
  let newContentOffset = CGPoint(x:0, y:contentOffset + 1)  
  tableView.setContentOffset(newContentOffset, animated: false)

  CATransaction.commit()
}


extension UITableView {
  typealias Updates = () -> Void

  func update(_ updates: Updates) {
    beginUpdates()
    updates()
    endUpdates()
  }
}

Thanks in advance.

1 Answers
Related