2012-10-18 30 views
5

我正在学习Core Animation并试用示例示例。CATransaction设置动画持续时间不起作用

当我使用下面的代码时,动画的持续时间工作

@implementation ViewController 

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

//Modifying base layer 
self.view.layer.backgroundColor = [UIColor orangeColor].CGColor; 
self.view.layer.cornerRadius = 20.0; 
self.view.layer.frame = CGRectInset(self.view.layer.frame, 20, 20); 

//Adding layer 
mylayer=[CALayer layer]; //mylayer declared in .h file 
mylayer.bounds=CGRectMake(0, 0, 100, 100); 
mylayer.position=CGPointMake(100, 100); //In parent coordinate 
mylayer.backgroundColor=[UIColor redColor].CGColor; 
mylayer.contents=(id) [UIImage imageNamed:@"glasses"].CGImage; 

[self.view.layer addSublayer:mylayer]; 
} 


- (IBAction)Animate //Simple UIButton 
{ 
[CATransaction begin]; 

// change the animation duration to 2 seconds 
[CATransaction setValue:[NSNumber numberWithFloat:2.0f] forKey:kCATransactionAnimationDuration]; 

mylayer.position=CGPointMake(200.0,200.0); 
mylayer.zPosition=50.0; 
mylayer.opacity=0.5; 

[CATransaction commit]; 
} 
@end 

在另一方面,如果我在viewDidLoad中按钮,以便它发生不按压任何按钮的底部集总的动画的方法的代码,动画持续时间不受尊重。我只看到没有任何动画的最终结果。

有什么想法?

感谢 九巴

回答

16

这里就是你缺少的信息:有在你的应用程序层的层次结构。有模型层次结构,您通常使用它。然后是演示图层层次结构,它反映了屏幕上的内容。看看“Layer Trees Reflect Different Aspects of the Animation State” in the Core Animation Programming Guide了解更多信息,或者(强烈推荐)观看来自WWDC 2011的Core Animation Essentials视频。

您编写的所有代码都在模型图层上运行(它应该如此)。

当系统从模型层中将更改的动画属性值复制到相应的表示层时,系统会添加隐式动画。

只有在UIWindow的视图层次结构中的模型图层才能获取表示层。在将self.view添加到窗口之前,系统会向您发送viewDidLoad,因此当viewDidLoad正在运行时,self.view或您的自定义层没有表示层。

所以你需要做的一件事就是稍后改变属性,在视图和图层被添加到窗口并且系统已经创建了表示层之后。 viewDidAppear:已经足够晚了。

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    //Modifying base layer 
    self.view.layer.backgroundColor = [UIColor orangeColor].CGColor; 
    self.view.layer.cornerRadius = 20.0; 
    self.view.layer.frame = CGRectInset(self.view.layer.frame, 20, 20); 

    // Adding layer 
    mylayer = [CALayer layer]; //mylayer declared in .h file 
    mylayer.bounds = CGRectMake(0, 0, 100, 100); 
    mylayer.position = CGPointMake(100, 100); //In parent coordinate 
    mylayer.backgroundColor = [UIColor redColor].CGColor; 
    mylayer.contents = (id)[UIImage imageNamed:@"glasses"].CGImage;  
    [self.view.layer addSublayer:mylayer]; 
} 

- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 

    [CATransaction begin]; { 
     [CATransaction setAnimationDuration:2]; 
     mylayer.position=CGPointMake(200.0,200.0); 
     mylayer.zPosition=50.0; 
     mylayer.opacity=0.5; 
    } [CATransaction commit]; 
} 
+0

感谢罗布。这工作。我猜这些括号开始提交是可选的。 – Spectravideo328

+0

大括号是可选的。我喜欢缩进'begin'和'commit'之间的代码,并且大括号使Xcode自动缩进它。 –

+0

我强烈推荐参考WWDC视频 - 这是一个很好的介绍了CoreAnimation的许多陷阱。 – MaxGabriel