Setting scroll position in UITableView

I think I’ve got a similar app: A list of item., tap ‘+’ -> new screen, come back and see the updated list, scrolled to show the added item at the bottom.

In summary, I put reloadData in viewWillAppear:animated: and scrollToRowAtIndexPath:... in viewDidAppear:animated:.

// Note: Member variables dataHasChanged and scrollToLast have been
// set to YES somewhere else, e.g. when tapping 'Save' in the new-item view.

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (dataHasChanged) {
        self.dataHasChanged = NO;
        [[self tableView] reloadData];
    } else {
        self.scrollToLast = NO; // No reload -> no need to scroll!
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (scrollToLast) {
        NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:([dataController count] - 1) inSection:0];
        [[self tableView] scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

I hope this helps. If you add something in the middle of the list, you could easily scroll to that position instead.

Leave a Comment