How to get notified when scrollToRowAtIndexPath finishes animating How to get notified when scrollToRowAtIndexPath finishes animating ios ios

How to get notified when scrollToRowAtIndexPath finishes animating


You can use the table view delegate's scrollViewDidEndScrollingAnimation: method. This is because a UITableView is a subclass of UIScrollView and UITableViewDelegate conforms to UIScrollViewDelegate. In other words, a table view is a scroll view, and a table view delegate is also a scroll view delegate.

So, create a scrollViewDidEndScrollingAnimation: method in your table view delegate and deselect the cell in that method. See the reference documentation for UIScrollViewDelegate for information on the scrollViewDidEndScrollingAnimation: method.


try this

[UIView animateWithDuration:0.3 animations:^{    [yourTableView scrollToRowAtIndexPath:indexPath                          atScrollPosition:UITableViewScrollPositionTop                                  animated:NO];} completion:^(BOOL finished){    //do something}];

Don't forget to set animated to NO, the animation of scrollToRow will be overridden by UIView animateWithDuration.

Hope this help !


To address Ben Packard's comment on the accepted answer, you can do this. Test if the tableView can scroll to the new position. If not, execute your method immediately. If it can scroll, wait until the scrolling is finished to execute your method.

- (void)someMethod{    CGFloat originalOffset = self.tableView.contentOffset.y;    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionMiddle animated:NO];    CGFloat offset = self.tableView.contentOffset.y;    if (originalOffset == offset)    {        // scroll animation not required because it's already scrolled exactly there        [self doThingAfterAnimation];    }    else    {        // We know it will scroll to a new position        // Return to originalOffset. animated:NO is important        [self.tableView setContentOffset:CGPointMake(0, originalOffset) animated:NO];        // Do the scroll with animation so `scrollViewDidEndScrollingAnimation:` will execute        [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionMiddle animated:YES];    }}- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{    [self doThingAfterAnimation];}