25

I have in iOS8 a table view like this:

tableView = UITableView(frame: view.bounds, style: .Plain)
view.addSubview(tableView)

When the user types and sends some text in the keyboard, the application ivoke the following method to scroll the tableView. The goal is to view the new text in the screen (like a chat)

let numberOfRows = tableView.numberOfRowsInSection(0)
        if numberOfRows > 0 {
            let indexPath = NSIndexPath(forRow: numberOfRows-1, inSection: 0)
            tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: animated)
        }

But the table view does not scroll to the bootom.

Someone has a solution?

Thank you.

Explanation:

Definition of the class:

class ChatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate 

then I have the definition of the table view:

var tableView: UITableView! 

in viewDidLoad:

tableView = UITableView(frame: view.bounds, style: .Plain) 
tableView.dataSource = self 
tableView.delegate = self 
view.addSubview(tableView) 

then I have the call to the code that should make the scroll (second block of code on my answer). When I launch the application I expect the tableview to scroll down, but it does not work.

17 Answers 17

89

The solution below worked for me. It's a combination of solutions found on StackOverflow. I called "scrollToRowAtIndexPath" after a very short delay.

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.tableView.numberOfSections()
        let numberOfRows = self.tableView.numberOfRowsInSection(numberOfSections-1)

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

    })
}

called by :

tableViewScrollToBottom(true)

Swift 3

func tableViewScrollToBottom(animated: Bool) {
    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) {
        let numberOfSections = self.tableView.numberOfSections
        let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)

        if numberOfRows > 0 {
            let indexPath = IndexPath(row: numberOfRows-1, section: (numberOfSections-1))
            self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: animated)
        }
    }
}
7
  • 2
    This is the best solution I found so far. I had to increase the delay to 0.5 though otherwise it would sometimes be called before tableView.reloadData has finished. I tried about every solution on SO (subclass TableViewDelegate and override reloadData; execute on main thread with dispatch_asynch, etc.) to scroll to bottom, none of them seem to work anymore for iOS 9.
    – Manuel
    Oct 17, 2015 at 22:50
  • iOS 9 broke other methods for scrolling to the bottom of a table. But this one works.
    – jcady
    Jan 15, 2016 at 21:30
  • This didn't help me ....I have to scroll manually to see the contents for last row. there is nothing wrong with table view and its content size because manual scroll shows the contents properly. May 19, 2017 at 15:16
  • 1
    It works but i wonder if there is any way to do this without dispatch after? Sep 25, 2017 at 13:36
  • Using "DispatchQueue" worked for me too in 2019, with Swift 5. scrollToRow was not working without delaying it by using "DispatchQueue". Can someone please explain its reason? Why a delay is necessary?
    – Luke
    Jul 20, 2019 at 7:15
11

The solution at my problem is:

let numberOfSections = tableView.numberOfSections()
let numberOfRows = tableView.numberOfRowsInSection(numberOfSections-1)

if numberOfRows > 0 {
    println(numberOfSections)
    let indexPath = NSIndexPath(forRow: numberOfRows-1, inSection: (numberOfSections-1))
    tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: animated)
}
1
  • 1
    cause crash in let numberOfRows = tableView.numberOfRowsInSection(numberOfSections-1) if numberOfSections is 0
    – jose920405
    May 20, 2016 at 13:38
8

SWIFT 3 VERSION of @Fox5150 answer, with an extension :

extension UITableView {

    func tableViewScrollToBottom(animated: Bool) {

        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {

            let numberOfSections = self.numberOfSections
            let numberOfRows = self.numberOfRows(inSection: numberOfSections-1)
            if numberOfRows > 0 {
                let indexPath = IndexPath(row: numberOfRows-1, section: (numberOfSections-1))
                self.scrollToRow(at: indexPath, at: UITableViewScrollPosition.bottom, animated: animated)
            }
        }
    }
}

USAGE:

self.tableView.tableViewScrollToBottom(animated: true)
0
6

Try reloading first before calling scroll. Very weired but works for iOS8.

   tableView.reloadData()
   tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: animated)
1
  • I needed to update a table view's scroll position that isn't visible when the scroll is taking place and this worked for me. Tested on iOS9. Also, It's not that it didn't scroll, but it didn't scroll completely in all instances. Now it does.
    – nmdias
    Mar 8, 2016 at 9:54
3

Swift 5 Version

extension UITableView {
  func tableViewScrollToBottom(animated: Bool) {
    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) {
      let numberOfSections = self.numberOfSections
      let index = self.numberOfRows(inSection: 0)
      if index > 0 {
        let indexPath = IndexPath(row: index-1, section: 0)
        self.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.bottom, animated: animated)
      }
    }
  }
}

You can use like:

[YOUR_TABLE_VIEW].tableViewScrollToBottom(animated: [TRUE])
1
2

I have the problem with a bigger index say even 15. Only indexes till 5-6 use to work. By making "animated: false" scrollToRowAtIndexPath() worked perfectly.

2

It's simple. Just do the scroll operation in viewDidLayoutSubViews()

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.scrollToBottom(animated: false)
}

fileprivate func scrollToBottom(animated: Bool) {
    if self.items.count > 0 {
        let lastIndex = IndexPath(row: items.count - 1, section: 1)
        self.tableView.scrollToRow(at: lastIndex, at: .bottom, animated: animated)
    }
}

It seems like tableview could get the correct positon after layout subviews.

0
1

The better solution is to flip upside down the tableView so you can show new message just by -insertRowsAtIndexPaths:withRowAnimation:

to do it you need first to flip your table by:

_tableView.transform = CGAffineTransformMakeScale (1,-1);

then don't forget to flip back your cells, best place to do it in -awakeFromNib by subclassing:

- (void)awakeFromNib {
    [super awakeFromNib];
    self.contentView.transform = CGAffineTransformMakeScale (1,-1);

//if you have accessoryView
    self.accessoryView.transform = CGAffineTransformMakeScale (1,-1);
}
1
1

I solved the issue by calling scrollToRow() in the `viewWillLayoutSubviews()

1

Try below:

if tableView.numberOfRows(inSection: 0) > 0 {
    tableView.scrollToRow(at: IndexPath(row: ROW, section: SECTION), at: .top, animated: false)
}
1

I go the same problem in late 2020.

Since i really did not want some magic dispatch-timeout, i played around a bit. What helped (and was not mentioned here before) was a forced layout for the UITableView:

_viewTable.layoutIfNeeded()
_viewTable.scrollToRow(at:IndexPath(row:index, section:0), at:.middle, animated:false)
0

If the keyboard is still visible you have to set the UITableView's contentInset property to compensate for the keyboard height at the bottom of the screen. Otherwise your cell might be hidden behind the keyboard because the UITableView doesn't know that half of its content is hidden by it.

Or use a UITableViewController which handles that automatically.

4
  • A little more context is necessary then. Can you share more code please?
    – fluidsonic
    Oct 8, 2014 at 21:08
  • Definition of the class: class ChatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate the definition of the table view: var tableView: UITableView! in viewDidLoad: tableView = UITableView(frame: view.bounds, style: .Plain) tableView.dataSource = self tableView.delegate = self view.addSubview(tableView) ... cal to the code that sould make the scroll (second block of code on my answer). When I launch the application I expect the tableview scrolls down, but does not work
    – Kobazzo
    Oct 8, 2014 at 21:21
  • 1
    Please edit your original question to add new code. This is barely readable.
    – fluidsonic
    Oct 8, 2014 at 21:22
  • This is still not enough code to understand how and when you scroll to the last cell. Can you show the whole process from the point where the message is added until the scroll happens (which you already posted)? -- You should also check out SlackTextViewController - maybe you find it helpful as it seems to do what you're looking for.
    – fluidsonic
    Oct 8, 2014 at 21:57
0

Call scrollToLastPosition() method after loading the tableview like call from viewWillAppear( ) or after table view reload when some thing changed into tableview

func scrollToLastPosition() {
 if !message.isEmpty {
    let indexpath = NSIndexPath(forRow: message.count - 1 , inSection:     0)
    self.tableView.scrollToRowAtIndexPath(indexpath, atScrollPosition: .Bottom, animated: true)
}
}
0

Heres Swift 3 version

let numberOfSections = self.tableView.numberOfSections
let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)

if numberOfRows > 0 {
    let indexPath = NSIndexPath.init(row: numberOfRows-1, section: numberOfSections-1)
    self.tableView.scrollToRow(at: indexPath as IndexPath, at: UITableViewScrollPosition.bottom, animated: animated)
}
0
// First figure out how many sections there are
 let lastSectionIndex = self.tblTableView!.numberOfSections() - 1

// Then grab the number of rows in the last section

let lastRowIndex = 
self.tblTableView!.numberOfRowsInSection(lastSectionIndex) - 1

// Now just construct the index path

let pathToLastRow = NSIndexPath(forRow: lastRowIndex, inSection: lastSectionIndex)

// Make the last row visible
self.tblTableView?.scrollToRowAtIndexPath(pathToLastRow, atScrollPosition: UITableViewScrollPosition.None, animated: true)
-1

All above codes are fine, but in my case when I want to load the tableView as well as scroll to bottom of the tableView instantly when the controller loads, for that situation above methods are taking some time to scroll to the bottom of the tableView. So I have followed these codes.

Override tableView reload as

extension UITableView
{
    func reloadData(completion: @escaping ()->()) {
        UIView.animate(withDuration: 0, animations: { self.reloadData() })
        { _ in completion() }
    }
}

Written scroll to bottom method as follows:

func tableViewScrollToBottom
{
     if self.tblChat.contentSize.height > self.tblChat.frame.size.height
     {
         let offset:CGPoint = CGPoint(x: 0,y :self.tblChat.contentSize.height-self.tblChat.frame.size.height)
         self.tblChat.setContentOffset(offset, animated: false)
     }
 }

and then reload tableView when data loads completes from web service or from any core data entity:

tblChat.reloadData()
{
     self.tableViewScrollToBottom
}

Now its working smooth as I wanted.

1
  • This is not scrolling at all. And please, check the code as you're not using the arguments parentheses in your func
    – Ennabah
    Jul 18, 2017 at 1:18
-2

I know this is an older thread, but it's still relevant. Instead of dealing with timeouts that could sometimes fail to be well timed, use synchronous blocks on the main thread (normally not something I'd do, but we're talking milliseconds):

DispatchQueue.main.sync {
  // Reload code goes here...
  tableView.reloadData()
}

DispatchQueue.main.sync {
  // Row, section and other checks / initialization go here...
  tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}

This always works for me.

1
  • I will never support this solution as blocking main thread simply does not mean that we are just blocking UI, we might be blocking something else running on that queue. Apr 24, 2020 at 16:43

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.