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

淺唱寂寞╮ 提交于 2019-12-17 15:15:21

问题


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.


回答1:


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;



回答2:


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)



回答3:


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];
}


来源:https://stackoverflow.com/questions/2795900/how-can-i-get-the-uitableview-scroll-position-so-i-can-save-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!