Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a UITableview to go to the top of page on reload?

I am trying to get a UITableview to go to the top of the page when I reload the table data when I call the following from

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {      // A bunch of code...      [TableView reloadData]; } 

Along those same lines, I would also like to be able to go to a specific section when I reload the table data.

I tried placing the following, which seems applicable only to the row, before and after the reload, but nothing happens:

[TableView scrollToRowAtIndexPath:0 atScrollPosition:UITableViewScrollPositionTop  animated:YES]; 
like image 487
AppsToKnow Avatar asked Apr 04 '11 18:04

AppsToKnow


People also ask

How do I scroll to top Tableview?

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 does Tableview reload data do?

reloadData()Reloads the rows and sections of the table view.

Is UITableView scrollable?

UITableView scrolls back because it's content size is equal to it's frame (or near to it). If you want to scroll it without returning you need add more cells: table view content size will be large then it's frame.


2 Answers

After reading all of the answers here and elsewhere, I finally found a solution that works reliably and does not show the scrolling after the data is loaded. My answer is based on this post and my observation that you need a negative offset if you are using content insets:

func reloadAndScrollToTop() {     tableView.reloadData()     tableView.layoutIfNeeded()     tableView.contentOffset = CGPoint(x: 0, y: -tableView.contentInset.top) } 
like image 31
phatmann Avatar answered Sep 23 '22 22:09

phatmann


Here's another way you could do it:

Objective-C

[tableView setContentOffset:CGPointZero animated:YES]; 

Swift 3 and higher

tableView.setContentOffset(.zero, animated: true) 

Probably the easiest and most straight forward way to do it.

like image 100
Erik B Avatar answered Sep 22 '22 22:09

Erik B