UILabel的图层在制作动画时不会更新颜色

时间:2014-07-13 16:17:19

标签: ios objective-c cocoa-touch core-animation catransition

我使用UILabel为屏幕上的CATransition设置为“蒸发”动画。
我希望标签文字变为绿色,然后离开屏幕。

以下代码可以很好地“蒸发”标签,但在制作动画之前不会更改其颜色:

CATransition *transition = [CATransition animation];
transition.beginTime = CACurrentMediaTime();
transition.duration = 0.4;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromTop;

[self.displayLabel.layer addAnimation:transition forKey:@"evaporate"];

self.displayLabel.textColor = [self greenColor];
self.displayLabel.text = @" ";

在标签上调用setNeedsDisplay不起作用 无法使用CABasicAnimation,因为标签文字正在发生变化。

我做错了什么以及如何解决?

1 个答案:

答案 0 :(得分:2)

你基本上想要嵌套动画,或者在某种意义上,你想要一个完整块类型的东西 我能想到的最接近的是使用CATransition委托

实施例

-(IBAction)btnTest:(UIButton *)sender
{
    //[1] Animate text color change

    CATransition *animation = [CATransition animation];
    [animation setDelegate:self]; //important
    [animation setRemovedOnCompletion:YES]; //better to remove the animation
    [animation setBeginTime:CACurrentMediaTime()]; //not really needed
    [animation setDuration:0.4];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [animation setType:kCATransitionFade];

    //you can specify any key name or keep it nil. doesn't make a difference
    [self.displayLabel.layer addAnimation:animation forKey:@"changeTextColor"];
    [self.displayLabel setTextColor:[UIColor greenColor]];
}

#pragma mark - CATransition Delegate
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //[2] Animate text sublayer

    /*
     The following CATransition should not set a delegate
     otherwise this animation will loop continously
    */

    CATransition *animation = [CATransition animation];
    [animation setRemovedOnCompletion:YES]; //better to remove the animation
    [animation setBeginTime:CACurrentMediaTime()]; //not really needed
    [animation setDuration:0.4];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [animation setType:kCATransitionPush];
    [animation setSubtype:kCATransitionFromTop];

    //you can specify any key name or keep it nil. doesn't make a difference
    [self.displayLabel.layer addAnimation:animation forKey:@"changeText"];
    [self.displayLabel setText:@" "];
}