LightNight
LightNight

Reputation: 1625

CABasicAnimation how to make it easy

I'm currently using the following animation on a UITableViewCell:

CATransform3D rotationTransform = CATransform3DMakeRotation(1.0f * M_PI, 0, 0, 1.0);
CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];

rotationAnimation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
rotationAnimation.duration = 0.25f;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = 1;

[cell.rotatingImage.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

However, when ~3 cells are animated as above the animations become very laggy. Is there any way I can reduce this lag?

Upvotes: 6

Views: 2094

Answers (1)

haroldcampbell
haroldcampbell

Reputation: 1542

The first things that I would is remove the animation creation code from the -tableView:cellForRowAtIndexPath: method to (say) the viewDidLoad. Then add the animation to the cell in the -tableView:cellForRowAtIndexPath: method.

Object creation and matrix calculations are expensive, so doing them for each call to the -tableView:cellForRowAtIndexPath: is going to slow down your code.

In code, I'd have something similar to the following:

- (void) viewDidLoad 
{
    // Normal viewDidLoad code above
    ...

    // Assume that rotationAnimation is an instance variable of type CABasicAnimation*;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];

    CATransform3D rotationTransform = CATransform3DMakeRotation(1.0f * M_PI, 0, 0, 1.0);

    rotationAnimation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
    rotationAnimation.duration = 0.25f;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // create cell
    ...
    // Now apply the animation to the necessary layer.
    [cell.rotatingImage.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

    return cell;
}

Does this do it?

Upvotes: 1

Related Questions