How do i automatically scroll in a table view? (Swift)
You have to call the method scrollToRowAtIndexPath
in the following way :
var indexPath = NSIndexPath(forRow: numberOfRowYouWant, inSection: 0)
self.tableview.scrollToRowAtIndexPath(indexPath,
atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
The above example assume you have only one section. I hope this help you.
For Swift 3:
let indexPath = NSIndexPath(item: numberOfRowYouWant, section: 2)
tableView.scrollToRow(at: indexPath as IndexPath, at: UITableViewScrollPosition.middle, animated: true)
For Swift 4:
let indexPath = NSIndexPath(item: numberOfRowYouWant, section: 2)
tableView.scrollToRow(at: indexPath as IndexPath, at: UITableView.ScrollPosition.middle, animated: true)
For Swift 5 ( Xcode 11.2.1 ):
let numberOfSections = self.tableView.numberOfSections
let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)
let indexPath = IndexPath(row: numberOfRows-1 , section: numberOfSections-1)
self.tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
For Swift 2:
let numberOfSections = self.tableView.numberOfSections
let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)
let indexPath = IndexPath(row: numberOfRows-1 , section: numberOfSections-1)
self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.middle, animated: true)
If you want scroll down automatically:
numberOfSections = tableView.numberOfSections()
let numberOfRows = tableView.numberOfRowsInSection(numberOfSections-1)
var indexPath = NSIndexPath(forRow: numberOfRows, inSection: numberOfSections)
self.tableview.scrollToRowAtIndexPath(indexPath,
atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
Swift 4:
let numberOfSections = tableView.numberOfSections
let numberOfRows = tableView.numberOfRows(inSection: numberOfSections - 1)
let indexPath = NSIndexPath(row: numberOfRows, section: numberOfSections)
self.tableView.scrollToRow(at: indexPath as IndexPath,
at: UITableView.ScrollPosition.middle, animated: true)