Search code examples
iosobjective-cuitableviewreloaddata

Animate [tableView reloadData]


I have a UITableViewCell that expands and adds a label on click.

Logic:

I added a label in cellForRowAtIndexPath to the selected cell, and in didSelectRow... I reloaded the tableView. In heightForRow... the selected cell expands. Hope you get the picture.

In didSelectRow... I have to reloadData, and not begin/end update. What I want to do is reloadData and have it animate. I can do like this:

[UIView transitionWithView: tableView
                  duration: 0.40f
                   options: UIViewAnimationOptionTransitionCrossDissolve
                animations: ^(void)
 {
   [self.tableView reloadData];
 }
                completion: nil
 }];

So that does a cross dissolve of the cells that is changing. What I want is UITableViewRowAnimationTop, but apparently that is not possible in the transition options. Is there a way to reloadData and use UITableViewRowAnimationTop?


Solution

  • [UITablewView reloadData:] is not animatable. However, you may want to try reloading tableView by reloading all sections with animation.

    NSIndexSet *sections = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [tableView numberOfSections])];
    
    [self.tableView reloadSections:sections withRowAnimation:UITableViewRowAnimationAutomatic];
    

    OK, I lied. It may be animatable but it requires much knowledge about how QuartzCore Framework operates on UI components.

    @import QuartzCore;
    

    [self.tableView reloadData];
    
    CATransition *transition = [CATransition animation];
    transition.type = kCATransitionPush;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.fillMode = kCAFillModeForwards;
    transition.duration = 0.6;
    transition.subtype = kCATransitionFromTop;
    
    [self.tableView.layer addAnimation:transition forKey:@"UITableViewReloadDataAnimationKey"];