Animating a pulsing UILabel?

Posted by fuzzygoat on Stack Overflow See other posts from Stack Overflow or by fuzzygoat
Published on 2011-02-17T21:51:15Z Indexed on 2011/02/22 15:25 UTC
Read the original article Hit count: 290

Filed under:
|
|

I am trying to animate the color the the text on a UILabel to pulse from: [Black] to [White] to [Black] and repeat.

- (void)timerFlash:(NSTimer *)timer {
[[self navTitle] setTextColor:[[UIColor whiteColor] colorWithAlphaComponent:0.0]];
[UIView animateWithDuration:1
                      delay:0 
                    options:UIViewAnimationOptionAllowUserInteraction 
                 animations:^{[[self navTitle] setTextColor:[[UIColor whiteColor] colorWithAlphaComponent:1.0]];} 
                 completion:nil];
}

.

[self setFadeTimer:[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFlash:) userInfo:nil repeats:YES]];

Firstly I am not sure of my method, my plan (as you can see above) was to set up a animation block and call it using a repeating NSTimer until canceled.

My second problem (as you can see above) is that I am animating from black (alpha 0) to white (alpha 1) but I don't know how to animate back to black again so the animation loops seamlessly

Essentially what I want is the text color to pulse on a UILabel until the user presses a button to continue.

EDIT_001:

I was getting into trouble because you can't animate [UILabel setColor:] you can however animated [UILabel setAlpha:] so I am going to give that a go.

EDIT_002:

- (void)timerFlash:(NSTimer *)timer {
    [[self navTitle] setAlpha:0.5];
    [UIView animateWithDuration:2 
                          delay:0 
                        options:UIViewAnimationOptionAllowUserInteraction 
                     animations:^{[[self navTitle] setAlpha:0.9];} 
                     completion:nil];
}

This works (BTW: I do want it to stop which is why I hooked it up to a NSTimer so I can cancel that) the only thing is that this animates from midGray to nearWhite and then pops back. Does anyone know how I would animate back from nearWhite to midGray so I get a nice smooth cycle? enter image description here

EDIT_003: (Solution)

The code suggested by dave DeLong (see below) does indeed work when modified to use the CALayer opacity style attribute:

UILabel *navTitle;
@property(nonatomic, retain) UILabel *navTitle;

.

// ADD ANIMATION
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"opacity"];
[anim setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[anim setFromValue:[NSNumber numberWithFloat:0.5]];
[anim setToValue:[NSNumber numberWithFloat:1.0]];
[anim setAutoreverses:YES];
[anim setDuration:0.5];
[[[self navTitle] layer] addAnimation:anim forKey:@"flash"];

.

// REMOVE ANIMATION
[[[self navTitle] layer] removeAnimationForKey:@"flash__"];

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c