Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView - scroll to the top

In my table view I have to scroll to the top. But I cannot guarantee that the first object is going to be section 0, row 0. May be that my table view will start from section number 5.

So I get an exception, when I call:

[mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; 

Is there another way to scroll to the top of table view?

like image 730
Ilya Suzdalnitski Avatar asked Apr 07 '09 09:04

Ilya Suzdalnitski


People also ask

How to scroll to top UITableView swift?

To scroll to the top of our tableview we need to create a new IndexPath . This index path has two arguments, row and section . All we want to do is scroll to the top of the table view, therefore we pass 0 for the row argument and 0 for the section argument. UITableView has the scrollToRow method built in.

What is scroll view in Swift?

Overview. UIScrollView is the superclass of several UIKit classes, including UITableView and UITextView . A scroll view is a view with an origin that's adjustable over the content view. It clips the content to its frame, which generally (but not necessarily) coincides with that of the application's main window.


2 Answers

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) 
like image 107
catlan Avatar answered Oct 19 '22 07:10

catlan


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]; 
like image 38
fabb Avatar answered Oct 19 '22 09:10

fabb