ios 如何为 UILabel 的背景颜色设置动画?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3762561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to animate the background color of a UILabel?
提问by Michiel de Mare
This looks like it should work, but doesn't. The color turns green at once.
这看起来应该有效,但没有。颜色一下子变成绿色。
self.labelCorrection.backgroundColor = [UIColor whiteColor];
[UIView animateWithDuration:2.0 animations:^{
self.labelCorrection.backgroundColor = [UIColor greenColor];
}];
回答by bosmacs
I can't find it documented anywhere, but it appears the backgroundColor
property of UILabel
is not animatable, as your code works fine with a vanilla UIView
. This hack appears to work, however, as long as you don't set the background color of the label view itself:
我在任何地方都找不到它的记录,但它的backgroundColor
属性似乎UILabel
不可动画,因为您的代码在 vanilla 上运行良好UIView
。但是,只要您不设置标签视图本身的背景颜色,此 hack 似乎就可以工作:
#import <QuartzCore/QuartzCore.h>
...
theLabel.layer.backgroundColor = [UIColor whiteColor].CGColor;
[UIView animateWithDuration:2.0 animations:^{
theLabel.layer.backgroundColor = [UIColor greenColor].CGColor;
} completion:NULL];
回答by Suragch
Swift
迅速
(important) Set the UILabel's background color to clear (either in IB or in code). For example:
override func viewDidLoad() { super.viewDidLoad() myLabel.backgroundColor = UIColor.clear }
Animate the layer background color.
@IBAction func animateButtonTapped(sender: UIButton) { UIView.animate(withDuration: 1.0, animations: { self.myLabel.layer.backgroundColor = UIColor.red.cgColor }) }
(重要)将 UILabel 的背景颜色设置为 clear(在 IB 中或在代码中)。例如:
override func viewDidLoad() { super.viewDidLoad() myLabel.backgroundColor = UIColor.clear }
动画图层背景颜色。
@IBAction func animateButtonTapped(sender: UIButton) { UIView.animate(withDuration: 1.0, animations: { self.myLabel.layer.backgroundColor = UIColor.red.cgColor }) }
Note that CGColor
is added after the UIColor
.
请注意,CGColor
在UIColor
.
Result
结果
回答by Mike Taverne
Swift 3
斯威夫特 3
To animate your label background color from white to green, set up your label like this:
要将标签背景颜色从白色设置为绿色,请按如下方式设置标签:
self.labelCorrection.backgroundColor = UIColor.clear
self.labelCorrection.layer.backgroundColor = UIColor.white.cgColor
Animate like this:
像这样制作动画:
UIView.animate(withDuration: 2.0) {
self.labelCorrection.layer.backgroundColor = UIColor.green.cgColor
}
To go back to the original state, so you can animate again, make sure you remove animations:
要返回原始状态,以便您可以再次设置动画,请确保删除动画:
self.labelCorrection.layer.backgroundColor = UIColor.white.cgColor
self.labelCorrection.layer.removeAllAnimations()
回答by software evolved
You CAN animate it, but I had to first set it (programmatically) to clearColor for some reason. Without that, the animation either didn't work or wasn't visible.
您可以为其设置动画,但出于某种原因,我必须首先将其(以编程方式)设置为 clearColor。没有它,动画要么不起作用,要么不可见。
I am animating the background color of a UILabel in a custom table cell. Here is the code in the willDisplayCell method. I wouldn't try to set the animation in cellForRow, since a lot of the layout gets tinkered with by the table.
我正在为自定义表格单元格中的 UILabel 的背景颜色设置动画。这里是在willDisplayCell方法的代码。我不会尝试在 cellForRow 中设置动画,因为很多布局都会被表格修改。
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
((RouteListCell *)cell).name.backgroundColor = [UIColor clearColor];
[((RouteListCell *)cell).name backgroundGlowAnimationFromColor:[UIColor whiteColor] toColor:[UIColor redColor] clearAnimationsFirst:YES];
}
Here's my animation routine:
这是我的动画例程:
-(void) backgroundGlowAnimationFromColor:(UIColor *)startColor toColor:(UIColor *)destColor clearAnimationsFirst:(BOOL)reset;
{
if (reset)
{
[self.layer removeAllAnimations];
}
CABasicAnimation *anAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
anAnimation.duration = 1.00;
anAnimation.repeatCount = HUGE_VAL;
anAnimation.autoreverses = YES;
anAnimation.fromValue = (id) startColor.CGColor; // [NSNumber numberWithFloat:1.0];
anAnimation.toValue = (id) destColor.CGColor; //[NSNumber numberWithFloat:0.10];
[self.layer addAnimation:anAnimation forKey:@"backgroundColor"];
}
回答by Techie
Please try this,
请试试这个,
[UIView transitionWithView:yourView duration:0.2 options:UIViewAnimationOptionTransitionNone animations:^{
[yourView setBackgroundColor:[UIColor colorWithRed:0.8588 green:0.8588 blue:0.8588 alpha:1]];
}completion:^(BOOL finished) {
}];
It works for me.
这个对我有用。
回答by Jiri Trecak
I recently came across this problem once again and after some research I figured that basically nothing changed (and probably won't in foreseeable future), so I ended up using Facebook POP framework(not only) for that.
我最近再次遇到了这个问题,经过一些研究,我认为基本上没有任何改变(并且在可预见的未来可能不会改变),所以我最终为此使用了 Facebook POP 框架(不仅如此)。
You can easily do animations of basic properties on both view and layer, but in addition, it provides smooth transition between colors (and basically whatever you want, even your custom types, with some additional coding). So for background color, you would do something like this:
您可以轻松地在视图和图层上制作基本属性的动画,但除此之外,它还提供颜色之间的平滑过渡(基本上任何您想要的,甚至您的自定义类型,还有一些额外的编码)。所以对于背景颜色,你会做这样的事情:
// Create spring animation (there are more types, if you want)
let animation = POPSpringAnimation(propertyNamed: kPOPViewBackgroundColor)
// Configure it properly
animation.autoreverses = false
animation.removedOnCompletion = true
animation.fromValue = UIColor.yourBeginningColor()
animation.toValue = UIColor.yourFinalColor()
// Add new animation to your view - animation key can be whatever you like, serves as reference
label.pop_addAnimation(animation, forKey: "YourAnimationKey")
Viola, now you can animate background colors on everything that has that property!
Viola,现在您可以为具有该属性的所有内容设置背景颜色动画!
回答by hotpaw2
Do the color animation manually, based off of an NSTimer or CADisplayLink callback at some reasonable frame rate (say 20 fps). You will have to calculate your own color change curve in RGB or HSV based on the fractional elapsed time over the full animation time (2.0 seconds in your example), or use an array of 40 intermediate colors.
根据 NSTimer 或 CADisplayLink 回调以某种合理的帧速率(例如 20 fps)手动执行彩色动画。您将必须根据整个动画时间(在您的示例中为 2.0 秒)中的部分经过时间计算您自己的 RGB 或 HSV 颜色变化曲线,或者使用 40 种中间颜色的数组。
回答by hfossli
it says in the docs that backgroundColor is animatable
它在文档中说 backgroundColor 是可动画的
Don't really know since when.
真的不知道从什么时候开始的。
回答by DavidN
If you don't want to dip down into Quartz, per answer one of the prev answers, create an empty UIView of same size as UILabel and position it in same spot as the UILabel (and in Z order, under it) and you can animate that UIView's background color (I've tried this, and it works for me).
如果您不想深入 Quartz,根据上一个答案之一的答案,创建一个与 UILabel 大小相同的空 UIView 并将其放置在与 UILabel 相同的位置(并按 Z 顺序,在其下方),您可以为 UIView 的背景颜色设置动画(我试过这个,它对我有用)。
回答by ThiagoAM
Swift 4.1 UILabel Extension:
Swift 4.1 UILabel 扩展:
Add this extension to your code:
将此扩展添加到您的代码中:
extension UILabel {
/** Animates the background color of a UILabel to a new color. */
func animateBackgroundColor(to color : UIColor?, withDuration : TimeInterval, completion : ((Bool) -> Void)? = nil) {
guard let newColor = color else { return }
self.backgroundColor = .clear
UIView.animate(withDuration: withDuration, animations: {
self.layer.backgroundColor = newColor.cgColor
}, completion: completion)
}
}
You should use it like this:
你应该像这样使用它:
myUILabel.animateBackgroundColor(to: .red, withDuration: 0.5)
Now, if you want to restore the original color, use it like this:
现在,如果你想恢复原来的颜色,像这样使用它:
// Storing the orignal color:
let originalColor = myUILabel.backgroundColor
// Changing the background color:
myUILabel.animateBackgroundColor(to: .red, withDuration: 0.5)
// ... Later:
// Restoring the original color:
myUILabel.animateBackgroundColor(to: originalColor, withDuration: 0.5, completion: {
(value: Bool) in
myUILabel.backgroundColor = originalColor
})