Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone SDK - How to scroll a UITableView programmatically with animation?

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.

like image 417
dan Avatar asked Mar 01 '10 21:03

dan


2 Answers

It works fine for me:

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

}

To be sure that this is called only once, you can make a verification like this:

if(!isInitialized){
   isInitialized = YES;
   ....
}
like image 99
mxg Avatar answered Oct 29 '22 16:10

mxg


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.

like image 45
Frank Schmitt Avatar answered Oct 29 '22 16:10

Frank Schmitt