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];
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.
reloadData()Reloads the rows and sections of the table view.
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.
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) }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With