CABasicAnimation如何让它变得简单

时间:2012-05-14 21:25:55

标签: iphone objective-c ios core-animation cabasicanimation

我目前正在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"];

但是,如上所述动画~3个细胞动画变得非常迟钝。有什么方法可以减少这种滞后吗?

1 个答案:

答案 0 :(得分:1)

我要做的第一件事就是将动画创建代码从-tableView:cellForRowAtIndexPath:方法移除到(比如说)viewDidLoad。然后将动画添加到-tableView:cellForRowAtIndexPath:方法中的单元格。

对象创建和矩阵计算非常昂贵,因此每次调用-tableView:cellForRowAtIndexPath:时执行这些操作都会降低代码速度。

在代码中,我会遇到类似以下的内容:

- (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;
}

这样做吗?