如果在添加子视图后直接将CATransition添加到子视图层,为什么CATransition不会工作?

时间:2012-03-04 04:47:25

标签: iphone core-animation

出于某种原因,如果在添加子视图后直接将动画添加到子视图的图层,则CATransition将不会设置动画:

transitionView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[transitionView setBackgroundColor:[UIColor redColor]];
[[self contentView] addSubview:transitionView];

CATransition *animation = [CATransition animation];
[animation setDelegate:self];
[animation setType:@"cube"];
[animation setDuration:1.0];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
[animation setSubtype:@"fromRight"];

[[transitionView layer] addAnimation:animation forKey:nil];

但如果在稍微延迟后添加动画:

transitionView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[transitionView setBackgroundColor:[UIColor redColor]];
[[self contentView] addSubview:transitionView];

CATransition *animation = [CATransition animation];
[animation setDelegate:self];
[animation setType:@"cube"];
[animation setDuration:1.0];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
[animation setSubtype:@"fromRight"];

[self performSelector:@selector(animate) withObject:nil afterDelay:0.00001];

-

- (void)animate
{
    CATransition *animation = [CATransition animation];
    [animation setDelegate:self];
    [animation setType:@"cube"];
    [animation setDuration:1.0];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
    [animation setSubtype:@"fromRight"];

    [[transitionView layer] addAnimation:animation forKey:nil];
}

转换将按预期工作。这有什么理由吗?

1 个答案:

答案 0 :(得分:9)

我也看到过这种行为。我认为这是因为该层位于您可以访问的“模型”层次结构中,但尚未添加到表示屏幕上实际内容的“真实”数据结构中。

无论如何,您可以使用[CATransaction flush]这样解决问题:

transitionView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[transitionView setBackgroundColor:[UIColor redColor]];
[[self contentView] addSubview:transitionView];

// Synchronize the implementation details with my changes so far.
[CATransaction flush];

CATransition *animation = [CATransition animation];
[animation setDelegate:self];
[animation setType:@"cube"];
[animation setDuration:1.0];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
[animation setSubtype:@"fromRight"];

[[transitionView layer] addAnimation:animation forKey:nil];