Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView scrollToRowAtIndexPath

Tags:

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"];
}
like image 261
Ali Shafai Avatar asked Sep 26 '09 00:09

Ali Shafai


1 Answers

Reload TableView data before calling scrollToRowAtIndexPath.

[contentTableView reloadData];
like image 133
William Rust Avatar answered Sep 29 '22 15:09

William Rust