1

Is there a way to change the foregroundColor of a UIView?

I'm creating an arrow using an UIView (drawRect) like this ">", with a clear background, only two black lines. This is working great. But afterwards I would like to change the color of the ">" from black to red, for example. Would be nice to have an animation in it, like a gradient from black to red, using CAKeyframeAnimation. I can do it for borderColor and backgroundColor but these properties are not the ones that I'm looking for.

I'm changing the borderColor of another UIView using this block of animation. I would like to do the same with the foregroundColor but it's not working in iOS.

CAKeyframeAnimation* colorAnim = [CAKeyframeAnimation animationWithKeyPath:@"borderColor"];
NSArray* colorValues = [NSArray arrayWithObjects:(id)[UIColor blackColor].CGColor,(id)[UIColor redColor].CGColor,  nil];
colorAnim.values = colorValues;
colorAnim.calculationMode = kCAAnimationPaced;
colorAnim.duration = 5.0;
colorAnim.repeatCount = 1;
[self.myView.layer addAnimation:colorAnim forKey:@"borderColor"];

I appreciate any help, thanks!

Fabio
  • 1,757
  • 19
  • 33

1 Answers1

0

The UIView class does not have a foregroundColor property, so you have to implement it yourself. In your UIView subclass interface, define the property:

@property (nonatomic, strong) UIColor *foregroundColor;

In your subclass implementation, override the setForegroundColor: setter method:

- (void)setForegroundColor:(UIColor *)newForegoundColor
{
    _foregroundColor = newForegroundColor;
    [self setNeedsDisplay]; // This is need so that drawRect: is called
}

In whichever initialiser you're are using in the subclass, set the foregroundColor property to a default:

self.foregroundColor = [UIColor blackColor];

In your drawRect: implementation, use the foregroundColor property to stroke the chevron you are drawing:

CGContextSetStrokeColorWithColor(context, self.foregroundColor.CGColor);
neilco
  • 7,964
  • 2
  • 36
  • 41
  • Hi, first of all, thank you very much for the answer. I did everything you suggested and the new property is working great, but the animation is not changing the color of the subview. I'm calling like this: `CAKeyframeAnimation* colorAnim2 = [CAKeyframeAnimation animationWithKeyPath:@"foregroundColor"];` `colorAnim2.values = colorValues;` `colorAnim2.calculationMode = kCAAnimationPaced;` `colorAnim2.duration = 5.0;` `colorAnim2.repeatCount = 1;` `[self.balloonTriangleBorder.layer addAnimation:colorAnim forKey:@"foregroundColor"];` – Fabio Oct 29 '13 at 11:48
  • To have a custom property be animatable, you have to do your drawing in the `CALayer` subclass and [override `needsDisplayForKey:`](http://stackoverflow.com/questions/14192816/create-a-custom-animatable-property). – neilco Oct 29 '13 at 11:57