Search code examples
iosobjective-cuitableviewanimationcell

Making tableView Cells Fall into place one after the other (tableViewCellAnimation)


I'm new to obj-C and I have this code which makes the cells slide in from the right of the page (when I call it after reloading the table data).

Instead of going through each one of them, waiting for the delay and then doing the next, they all slide in at the same time after the delay count.

Why are they sliding in all at once instead of staggering the animation?

-(void) animate {
  for (UITableViewCell * aCell in [self.tableView visibleCells]) {
    [aCell setFrame: CGRectMake(320, aCell.frame.origin.y, aCell.frame.size.width, aCell.frame.size.height)];
    [UIView animateWithDuration: 0.5 delay: 0.5 options: UIViewAnimationOptionBeginFromCurrentState animations: ^ {
      [aCell setFrame: CGRectMake(0, aCell.frame.origin.y, aCell.frame.size.width, aCell.frame.size.height)];
    }
    completion: nil
    ];

  }

Solution

  • I think you just don't understand how delay and blocks works. Let me try to clear this code:

    1. You go throw all [self.tableView visibleCells] array
    2. You call [UIView animateWithDuration:...] method number of times, how much elements in visibleCells array (delay doesn't freeze your code)
    3. In every method above starts 0.5 timer in another tread.
    4. After 0.5 seconds animation block calls number of times, how much elements visibleCells has

    For you easiest solution will be to save visible cells in any array, then call animation method with parameter - index of cell you will animate in this method. In completion block call next animation. Here is code example:

    - (void)animate:(NSInteger)index {
        if (visibaleCells.count <= index) {
            return;
        }
    
        [UIView animateWithDuration:0.5 delay:0.5 options:0 animations:^{
            [visibaleCells[index] setFrame:CGRectMake(0, aCell.frame.origin.y, aCell.frame.size.width, aCell.frame.size.height)];
        } completion:^(BOOL finished) {
            [self animate:index + 1];
        }];
    }