Search code examples
iphonecocoa-touchuitableviewviewdidload

Strange behaviour of UITableView scrollToRowAtIndexPath:


I have to set an initial scroll position of my UITableView to a row other than the first one (for example, the first row of the second section).

In my view controller's viewDidLoad I write:

- (void)viewDidLoad
{
    // self.view is a container view, not UITableView
    [super viewDidLoad];
    [table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]
       atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

When the screen loads, the scroll position is not set immediately. Otherwise, when the animated parameter is set to YES, the position is set immediately without any animation. What's going on?

What's the correct way to set initial row position for UITableView?


Solution

  • Best place should be ViewDidAppear. Moreover, you should invoke scroll method in cellWillDisplay to make sure. Remember to check indexPath before invoking scroll method