views:

719

answers:

3

How would I scroll a UITableView to a specific position with an animation?

Currently I'm using this code to jump to a position:

 //tableController -> viewDidLoad
 [self.tableView reloadData];
 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
 [self.tableView scrollToRowAtIndexPath:indexPath
                       atScrollPosition:UITableViewScrollPositionTop
                               animated:YES];

The problem with this code is, that the table jumps right to the right position without any animation. Is there any way to enable the animation or set the duration?

Thanks for any help.

A: 

I have two suggestions for you to investigate:

  1. Are you running your app on the simulator or the iPhone itself? I have noticed some animations behave differently in the simulator.

  2. Is it possible you are calling scrollToRowAtIndexPath:atScrollPosition:animated twice in quick succession? This can 'confuse' the animation. You should call this function only once while processing a given event.

richb
Thanks for your reply. I'm running the code on the device and calling this code in the viewDidLoad method.
dan
It may be that, for whatever reason, an animation can't be started from viewDidLoad because this is part of the view initialisation. I'm not saying I know why exactly that would be, but it sounds plausible. Try scheduling an event with NSRunLoop's performSelector, and do your scroll when that is called.
richb
+1  A: 

Try commenting out the reloadData call. If I'm understanding your question correctly, and you're in viewDidLoad, you should not need to call it anyway.

Also, if you've just gotten done pushing the view controller, you won't get an animated scroll. You'll have to insert a delay (I've found a quarter second works well) between the time that viewDidLoad was called and when your animation starts.

Frank Schmitt
A: 

It works very well for me:

-(void) viewDidAppear:(BOOL)animated{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:n inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath
                    atScrollPosition:UITableViewScrollPositionTop
                            animated:YES];

}

To be shore that this is called only one time, you can make a verification like:

if(!isInitialized){
   isInitialized = YES;
   ....
}
mxg