UITableView - scroll to the top
UITableView is a subclass of UIScrollView, so you can also use:
[mainTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
Or
[mainTableView setContentOffset:CGPointZero animated:YES];
And in Swift:
mainTableView.setContentOffset(CGPointZero, animated:true)
And in Swift 3 & above:
mainTableView.setContentOffset(.zero, animated: true)
Note: This answer isn't valid for iOS 11 and later.
I prefer
[mainTableView setContentOffset:CGPointZero animated:YES];
If you have a top inset on your table view, you have to subtract it:
[mainTableView setContentOffset:CGPointMake(0.0f, -mainTableView.contentInset.top) animated:YES];
Possible Actions:
1
func scrollToFirstRow() { let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)}
2
func scrollToLastRow() { let indexPath = NSIndexPath(forRow: objects.count - 1, inSection: 0) self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)}
3
func scrollToSelectedRow() { let selectedRows = self.tableView.indexPathsForSelectedRows if let selectedRow = selectedRows?[0] as? NSIndexPath { self.tableView.scrollToRowAtIndexPath(selectedRow, atScrollPosition: .Middle, animated: true) }}
4
func scrollToHeader() { self.tableView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true)}
5
func scrollToTop(){ self.tableView.setContentOffset(CGPointMake(0, UIApplication.sharedApplication().statusBarFrame.height ), animated: true)}
Disable Scroll To Top:
func disableScrollsToTopPropertyOnAllSubviewsOf(view: UIView) { for subview in view.subviews { if let scrollView = subview as? UIScrollView { (scrollView as UIScrollView).scrollsToTop = false } self.disableScrollsToTopPropertyOnAllSubviewsOf(subview as UIView) }}
Modify and use it as per requirement.
Swift 4
func scrollToFirstRow() { let indexPath = IndexPath(row: 0, section: 0) self.tableView.scrollToRow(at: indexPath, at: .top, animated: true) }