jpm
jpm

Reputation: 16702

How to reset the scroll position of a UITableView?

I would like to completely reset the scroll position of a UITableView, so that every time I open it, it is displaying the top-most items. In other words, I would like to scroll the table view to the top every time it is opened.

I tried using the following piece of code, but it looks like I misunderstood the documentation:

- (void)viewWillAppear:(BOOL)animated {
    [tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:NO];
}

Is this the wrong approach here?

Upvotes: 18

Views: 18857

Answers (4)

sash
sash

Reputation: 8715

Swift:

self.tableView.scrollRectToVisible(CGRect.zero, animated: false)

Upvotes: 0

Roberto LL
Roberto LL

Reputation: 112

What I ended up doing was this:

Swift 4

self.tableView.contentOffset = CGPoint.zero
DispatchQueue.main.async {
    self.tableView.reloadData()
}

Upvotes: 0

Mike McMaster
Mike McMaster

Reputation: 7591

August got the UITableView-specific method. Another way to do it is:

[tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];

This method is defined in UIScrollView, the parent class to UITableView. The above example tells it to scroll to the 1x1 box at 0,0 - the top left corner, in other words.

Upvotes: 34

August
August

Reputation: 12187

The method you're using scrolls to (as the method name implies) the nearest selected row. In many cases, this won't be the top row. Instead, you want to use either

scrollToRowAtIndexPath:atScrollPosition:animated:

or

selectRowAtIndexPath:animated:scrollPosition:

where you use the index path of the row you want to scroll to. The second method actually selects a row, the first method simply scrolls to it.

Upvotes: 6

Related Questions