Bram'in Bram'in - 1 year ago 88
iOS Question

Scroll down tableView in swift?

I have a table view which received data from a real-time database. These data are added from the bottom of the table view and so on this table view has to scroll down itself to show new data.

I've found a method to do it however I'm not satisfied because the scroll always start from the top of the list. Not very beautiful.

Here is the code of this method :

func tableViewScrollToBottom(animated: Bool) {

let delay = 0.1 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

dispatch_after(time, dispatch_get_main_queue(), {

let numberOfSections = self.clientTable.numberOfSections
let numberOfRows = self.clientTable.numberOfRowsInSection(numberOfSections-1)

if numberOfRows > 0 {
let indexPath = NSIndexPath(forRow: numberOfRows-1, inSection: (numberOfSections-1))
self.clientTable.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: animated)


Is there a way to modify this method in order to scroll only from the previous position ?

Rob Rob

The issue is probably how the rows were inserted into the table. For example, if you add rows to the end using something like this, you get a very smooth UI:

@IBAction func didTapAddButton(sender: AnyObject) {
    let count = objects.count
    var indexPaths = [NSIndexPath]()

    // add two rows to my model that `UITableViewDataSource` methods reference;
    // also build array of new `NSIndexPath` references

    for row in count ..< count + 2 {
        objects.append("New row \(row)")
        indexPaths.append(NSIndexPath(forRow: row, inSection: 0))

    // now insert and scroll

    tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .None)
    tableView.scrollToRowAtIndexPath(indexPaths.last!, atScrollPosition: .Bottom, animated: true)

Note, I don't reload the table, but rather call insertRowsAtIndexPaths. And I turned off the animation because I know they're off screen, and I'll then scroll to that row.

enter image description here