mardi 5 mai 2015

Using CABasicAnimation in a UIButton subclass

I would like to animate the transition of a button's border color when the highlighted state changes. I have subclassed UIButton and overridden setHighlighted, where I perform a CABasicAnimation. The problem is, this code is executed but the border color instantly changes - it doesn't animate from one color to the next. This same code worked when I used it in the view controller, causing me to wonder if CABasicAnimation doesn't work in a UIButton subclass, or what else is necessary to ensure this animation occurs.

How can I animate a button's CALayer's borderColor in the button subclass?

- (void)setHighlighted:(BOOL)highlighted {
    [super setHighlighted:highlighted];

    if (highlighted) {
        [self highlight];
    } else {
        [self unhighlight];
    }
}

- (void)highlight {
    UIColor *currentLayerColor = [[UIColor alloc] initWithCGColor:self.layer.borderColor];
    UIColor *newLayerColor = [currentLayerColor colorWithAlphaComponent:0.25];

    CABasicAnimation *color = [CABasicAnimation animationWithKeyPath:@"borderColor"];
    color.fromValue = (__bridge id)currentLayerColor.CGColor;
    color.toValue   = (__bridge id)newLayerColor.CGColor;
    self.layer.borderColor = newLayerColor.CGColor;

    color.duration = 2.0;
    [self.layer addAnimation:color forKey:nil];
}

- (void)unhighlight {
    UIColor *currentLayerColor = [[UIColor alloc] initWithCGColor:self.layer.borderColor];
    UIColor *newLayerColor = [currentLayerColor colorWithAlphaComponent:1.0];

    CABasicAnimation *color = [CABasicAnimation animationWithKeyPath:@"borderColor"];
    color.fromValue = (__bridge id)currentLayerColor.CGColor;
    color.toValue   = (__bridge id)newLayerColor.CGColor;
    self.layer.borderColor = newLayerColor.CGColor;

    color.duration = 2.0;
    [self.layer addAnimation:color forKey:nil];
}

Aucun commentaire:

Enregistrer un commentaire