views:

54

answers:

2

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?

A: 

Just a shot in the dark, but have you tried to put this code into viewDidAppear{}?

Dutchie432
Exactly the same result.
alexey
A: 

This won't work in viewDidLoad or viewWillAppear since the table most likely haven't been populated by then (at least it wasn't in my case)

Try putting it in an NSTimer instead once your table loads and calling it then.

As an aside, I quickly put this code (with animation) into a nav bar button item and it worked very well after the table was finished loading.

iWasRobbed
The scrolling works even in viewDidLoad, but it scrolls not immediately. NSTimer is some kind of hack to my mind. Is there any callback for table did load event?
alexey
Correct, it won't scroll until the data exists to scroll to. On projects where you have a large amount of tableview data or images, it can take 2 seconds or more and by then `viewDidLoad` was already called. Unfortunately there is nothing in the `UITableViewDelegate` method for when a table is done loading. You might find more info here: http://stackoverflow.com/questions/1483581/get-notified-when-uitableview-has-finished-asking-for-data
iWasRobbed
Not sure why I got a downvote on this one; care to elaborate?
iWasRobbed