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 *)pic
You must scroll UITableView at the first row of your table view by using this line of code:
self.yourTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
To scroll to a specific section you need to specify the index path to it:
NSIndexPath *topPath = [NSIndexPath indexPathForRow:0 inSection:0];
[TableView scrollToRowAtIndexPath:topPath
atScrollPosition:UITableViewScrollPositionTop
animated:YES];
If you are uncertain about the number of rows in your tableView. Use the following:
NSIndexPath *topPath = [NSIndexPath indexPathForRow:NSNotFound inSection:0];
[TableView scrollToRowAtIndexPath:topPath
atScrollPosition:UITableViewScrollPositionTop
animated:YES];
This is working for me.
tableView.scrollToRow(at: IndexPath.init(row: 0, section: 0), at: .top, animated: true)
After considering the options discussed above my version of the solutions is the following. It works consistently in iOS 11 & 12 for both UICollectionView & UITableView.
UICollectionView:
DispatchQueue.main.async { [weak self] in
guard self?.<your model object>.first != nil else { return }
self?.collectionView.scrollToItem(at: IndexPath(row: 0, section: 0),
at: .top,
animated: false)
}
UITableView:
DispatchQueue.main.async { [weak self] in
guard self?.<your model object>.first != nil else { return }
self?.collectionView.scrollToRow(at: IndexPath(row: 0, section: 0),
at: .top,
animated: false)
}
UITableView is a subclass of UIScrollView, so you can also use:
[mainTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
For those still finding solution to this, you can use the following extension of UITableView
.
Including a check where first section has row(s) or not. It goes till the section with row(s) comes and then scrolls to that one.
extension UITableView {
func scrollToFirst() {
self.reloadData() // if you don't want to reload data, remove this one.
for i in 0..<self.numberOfSections {
if self.numberOfRows(inSection: i) != 0 {
self.scrollToRow(at: IndexPath(row: 0, section: i), at: .top, animated: true)
break
}
}
}
}
Hope that helped you.