73

Is there any way to find out which UITableViewCell is at the top of the scroll window?

I'd like to get the current scroll position so that I can save it when the app exits. When the app gets started I want to scroll to the position it was at when it last exited.

jszumski
  • 7,430
  • 11
  • 40
  • 53
progrmr
  • 75,956
  • 16
  • 112
  • 147

3 Answers3

165

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;
Venk
  • 5,949
  • 9
  • 41
  • 52
Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172
  • 1
    That's a CGPoint in the scroll view, I'm not sure how I can tell which UITableViewCell that corresponds to. – progrmr May 08 '10 at 23:32
  • 15
    You don't need the cell if you use the offset; just set the offset when you re-enter the view. However, if you MUST know the cell at the top, just use: [tableView indexPathForRowAtPoint: CGPointMake(0, 0)]; – Ben Gottlieb May 09 '10 at 01:46
  • using contentOffset works perfectly, it returns the scroll position exactly where it was when the app last quit. Thanks! I didn't need to know which cell it was after all. – progrmr May 09 '10 at 21:22
  • for the c# user use this case: tableView.ContentOffset.Y; – Guillaume V Oct 31 '12 at 19:05
13

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)
Heinrisch
  • 5,835
  • 4
  • 33
  • 43
1

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];
}
coolcool1994
  • 3,704
  • 4
  • 39
  • 43