5

I am trying to animate backgroundColor property of UILabel class and being unsuccessful so far. Here the snippet of my code

-(void) blink {
  UIColor* originalColor = lblDescription.backgroundColor;
  lblDescription.backgroundColor = [UIColor yellowColor];

  [UIView beginAnimations:nil context:NULL];
  [UIView setAnimationDuration:1.0];
  lblDescription.backgroundColor = originalColor;
  [UIView commitAnimations];
}
//this code works if lblDescription is UIView and does not if UILabel

I found some claims that some UILabel properties are not animatable, but I couldn't substantiate that claim by reading Apple docs. I was wondering if someone can shed light on this problem.

bioffe
  • 6,283
  • 3
  • 50
  • 65

2 Answers2

4

On this page from the View Programming Guide For iOS, "Table 1-2 Animatable properties" supposedly lists all the animatable properties of UIViews. It doesn't include backgroundColor.

But on the UIView Class Reference, under the backgroundColor property it says:

Discussion
Changes to this property can be animated. The default is nil.

So it's not clear why the UILabel's backgroundColor does not animate.

The workaround I've used in the past is to use a CATextLayer instead of a UILabel.

  • Try these two other workarounds in [this question](http://stackoverflow.com/questions/2426614/how-to-animate-the-textcolor-property-of-an-uilabel). Those should work in earlier OS versions. –  Oct 26 '10 at 20:09
  • @aBitObvious CATextLayer doesn't have vertical alignment facilities(in iOS) and renders text at the top of its surface (UILabel renders in center). I am giving up :( – bioffe Nov 19 '10 at 23:39
  • @bioffe: The workaround that uses two UILabels overlapping each other is an easy workaround. Have you tried it? It's a bit annoying to have duplicate UILabels but then you just animate their alpha in reverse directions. –  Nov 20 '10 at 00:09
  • @aBitObvious That exactly what I was going to do next. Meanwhile I filed this hopeless bug issue with Apple. Thanks for your help. – bioffe Nov 20 '10 at 17:10
  • 1
    Here's a much better workaround using just the original UILabel itself: http://stackoverflow.com/questions/6442774/is-uilabels-backgroundcolor-not-animatable/6442868#6442868 –  Jun 22 '11 at 16:11
0

If you'd like to animate the color of a label (including the background) you can do something like this:

https://stackoverflow.com/a/20892927/189924

This does not involve layers or using multiple views.

Community
  • 1
  • 1
strange
  • 9,654
  • 6
  • 33
  • 47