How can I get the UITableView scroll position so I can save it?

3 Solutions Collect From Internet About “How can I get the UITableView scroll position so I can save it?”

You can easily grab the exact offset of the table view by looking at its contentOffset property. For the vertical scroll, look at:

tableView.contentOffset.y;

The accepted solution only works if you know the size of all table view items. With auto sizing/estimated size that is not always true.

One alternative is to save the first visible item and scroll to it.

You can get the first visible item indexPath with:

savedIndex = tableView.indexPathsForVisibleRows?.first

Then scroll to it by doing:

tableView.scrollToRowAtIndexPath(savedIndex, atScrollPosition: .Top, animated: false)

Make sure you can load in viewWillAppear and not viewDidLoad (tested iOS 9). ViewWillAppear is when view has finished layout – there is differences in the outcome.

-(void) viewWillAppear:(BOOL)animated {
    NSUserDefaults *lightData = [NSUserDefaults standardUserDefaults];
    [self.tableView setContentOffset:CGPointMake(0, [lightData floatForKey:@"yValue"])];
}

-(void) viewWillDisappear:(BOOL)animated {
    NSUserDefaults *lightData = [NSUserDefaults standardUserDefaults];
    [lightData setFloat:self.tableView.contentOffset.y forKey:@"yValue"];
    [lightData synchronize];
}