使用动画改变UILabel的背景色

使用动画改变UILabel的背景色


当设置了UIView的backgroundColor,再去动画改变UILabel的背景色会失败

//设置背景色
label.backgroundColor = [UIColor redColor];

...

//动画修改背景色
CABasicAnimation* cocorAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
CGColorRef originColor = [UIColor whiteColor].CGColor;
CGColorRef darkGray = [UIColor blueColor].CGColor;

cocorAnimation.fromValue = (__bridge id)originColor;
cocorAnimation.toValue = (__bridge id)darkGray;

cocorAnimation.duration = 0.8;
[self.label.layer addAnimation:cocorAnimation forKey:@""];

效果是 UILabel的背景色一点也没改变。。


修改使用layer的backgroundColor

//设置背景色
label.layer.backgroundColor = [UIColor redColor].CGColor;

...

//动画修改背景色
CABasicAnimation* cocorAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
CGColorRef originColor = [UIColor whiteColor].CGColor;
CGColorRef darkGray = [UIColor blueColor].CGColor;

cocorAnimation.fromValue = (__bridge id)originColor;
cocorAnimation.toValue = (__bridge id)darkGray;

cocorAnimation.duration = 0.8;
[self.label.layer addAnimation:cocorAnimation forKey:@""];

这次动画成功了。

参考链接how-to-animate-the-background-color-of-a-uilabel

原文地址:https://www.cnblogs.com/sunyanyan/p/5253047.html