2012-03-04 93 views
3

出于某种原因,如果动画添加到子视图的层添加子视图之后直接CATransition将无法运行动画:如果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"]; 

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

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]; 

但是如果动画稍有延迟后添加

-

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

如预期的转变将工作。这有什么理由吗?

回答

7

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

无论如何,你可以解决它通过使用[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]; 
+1

此外,您可能要设置背景颜色为'clearColor'刷新之前,再经过其更改为'redColor'冲洗。 – 2012-03-04 05:09:37

相关问题