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.
All above codes are fine, but in my case when I want to load the
tableView
as well as scroll to bottom of thetableView
instantly when the controller loads, for that situation above methods are taking some time to scroll to the bottom of thetableView
. So I have followed these codes.Override
tableView
reload asWritten scroll to bottom method as follows:
and then reload
tableView
when data loads completes from web service or from any core data entity:Now its working smooth as I wanted.
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):
This always works for me.
It's simple. Just do the scroll operation in viewDidLayoutSubViews()
It seems like tableview could get the correct positon after layout subviews.
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.
If the keyboard is still visible you have to set the
UITableView
'scontentInset
property to compensate for the keyboard height at the bottom of the screen. Otherwise your cell might be hidden behind the keyboard because theUITableView
doesn't know that half of its content is hidden by it.Or use a
UITableViewController
which handles that automatically.