I'm trying to make my table view remember it's last position, so that after the app is run again, it will scroll to that position. to do this, in my viewWillDisappear:
method, I get the first visible row number and save it to NSUserDefaults
. then in my viewDidAppear I try to scroll to that row by sending scrollToRowAtIndexPath
to the table view. However I get a NSRangeException
:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '-[UITableView scrollToRowAtIndexPath:atScrollPosition:animated:]: section (0) beyond bounds (0).
any help appreciated. Here is the code:
- (void)viewDidAppear:(BOOL)animated
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if ([userDefaults valueForKey:@"content_row"] != nil)
{
int rowToHighlight = [[userDefaults valueForKey:@"content_row"] intValue];
NSIndexPath * ndxPath= [NSIndexPath indexPathForRow:rowToHighlight inSection:0];
[contentTableView scrollToRowAtIndexPath:ndxPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
}
-(void) viewWillDisappear:(BOOL)animated
{
NSIndexPath *selectedRowPath = [[contentTableView indexPathsForVisibleRows] objectAtIndex:0];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:selectedRowPath.row forKey:@"content_row"];
}
Reload TableView data before calling scrollToRowAtIndexPath.
[contentTableView reloadData];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With