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

3

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.

Massage answered 8/5, 2010 at 22:32 Comment(1)
This can also be achieved as <#55327730>Hemispheroid
B
166

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;
Boatswain answered 8/5, 2010 at 22:41 Comment(4)
That's a CGPoint in the scroll view, I'm not sure how I can tell which UITableViewCell that corresponds to.Massage
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)];Boatswain
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.Massage
for the c# user use this case: tableView.ContentOffset.Y;Milks
S
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)
Shakti answered 7/9, 2016 at 13:31 Comment(0)
R
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];
}
Reifel answered 28/10, 2016 at 3:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.