Best method to get text to blink in iPhone OS?

2019-03-31 04:54发布

问题:

I want my text box to blink (like the old LCD clocks).

Right now, I'm calling a myriad of NSTimers and selectors that wait, change the alpha, wait, then change it back. Even with this, it looks really bad, and I'm thinking I have to put an NSTimer to gradually change the alpha, but from what I hear they are not meant for things of that precision.

My thoughts are there must be a way to do this a lot better than how I am currently implementing it. It feels like hack.

回答1:

Using an animation delegate might make it less "hacky":

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[myLabel setAlpha:0.0];
[UIView commitAnimations];

And then you can have your didStopSelector restart the animation:

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    [self displayLabel];
}

Depending on the animationID, you could take different actions, etc. Using UIView's setAnimationDelay might come in handy as well.

UIView also has a setDuration call for animations:

[UIView setAnimationDuration:0.1];

If you are building for iOS4, check the documentation since you should be using block-based animation calls rather than these delegate based ones.



回答2:

you can set the alpha of the lable with annimation just like

to hide lable with animation

[UIView animateWithDuration:0.2 delay:0.1 options:UIViewAnimationOptionCurveEaseOut animations:^{
        lblDistance.alpha=0;
    } completion:^(BOOL finished) {
        if (finished) {

        }
    }];

to show lable with animation

[UIView animateWithDuration:0.2 delay:0.1 options:UIViewAnimationOptionCurveEaseOut animations:^{
        lblDistance.alpha=1;
    } completion:^(BOOL finished) {
        if (finished) {

        }
    }];

this is the best way anyone can animate and create a blinking lable........



回答3:

I would use an NSTimer, but instead of messing with alpha channels i would either not draw the text (if that's even possible with Apple's very attribute-limited SDK), or if that's not possible you could always draw something on top of it (like a rectangle).

Using this approach of drawing something over your text would yield better performance. Though some (okay most) would consider this a ugly hack, let me just say this, "If it looks right, it is right."



回答4:

NSTimers and changing the alpha is a perfectly acceptable way of doing it - that's certainly what I do. If you are having problems, perhaps a code sample might help us see where the issue is?