Blinking effect on UILabel
Asked Answered
D

14

28

I have a UILabel with background color as grey.

I want a blinking effect on this label like it should become a little white & then become gray and it should keep happen till I turn it off programatically.

Any clue how to achieve this?

Devinna answered 3/6, 2011 at 7:58 Comment(1)
extension UIView{ func blink() { self.alpha = 0.2 UIView.animate(withDuration: 1, delay: 0.0, options: [.curveLinear, .repeat, .autoreverse], animations: { self.alpha = 1.0 }, completion: nil) } }Farnese
S
22

Use NSTimer

NSTimer *timer = [NSTimer 
                      scheduledTimerWithTimeInterval:(NSTimeInterval)(1.0)
                            target:self 
                             selector:@selector(blink) 
                             userInfo:nil 
                             repeats:TRUE];
BOOL blinkStatus = NO;

in your blink function

-(void)blink{
   if(blinkStatus == NO){
      yourLabel.backgroundColor = [UIColor whiteColor];
     blinkStatus = YES;
   }else {
      yourLabel.backgroundColor = [UIColor grayColor];
      blinkStatus = NO;
   }
}
Spectroscopy answered 3/6, 2011 at 8:12 Comment(4)
Shouldn't you use BOOL, YES and NO rather than bool, TRUE and FALSE ? Thx.Promiscuous
@Promiscuous Yes. One of my early(nostalgic) iOS programming bad practices. Corrected now. Thanks for noting that.Spectroscopy
@Spectroscopy Speaking of bad practices. Repeating timers at 60fps... this should be an animation (there is discrete animations for when you don't want any interpolation between the values)Existence
Nice. The UIView animation example work on fading the alpha. OP wanted a BLINK effect. This does it.Insubstantial
A
57

You can do this within a block:

self.yourLabel.alpha = 1;
[UIView animateWithDuration:1.5 delay:0.5 options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{
        self.yourLabel.alpha = 0;
} completion:nil];

So you dont need a second method.

Anderson answered 4/2, 2014 at 17:2 Comment(2)
This is a nice alternative, although it's more of a slow fade in/out than a blink. Note you can stop the animation by using [self.yourLabel.layer removeAllAnimations].Asserted
you could .alpha = 1; the first time and in the animation block .alpha = 0; this will avoid a weird blinking at the start of the animation.Priggery
E
34

Swift 3

extension UILabel {

    func startBlink() {
        UIView.animate(withDuration: 0.8,
              delay:0.0,
              options:[.allowUserInteraction, .curveEaseInOut, .autoreverse, .repeat],
              animations: { self.alpha = 0 }, 
              completion: nil)
    }

    func stopBlink() {
        layer.removeAllAnimations()
        alpha = 1
    }
}
Epigene answered 8/10, 2016 at 20:8 Comment(3)
if i have a button named "btn" how would i call the function to start?Cymophane
Within the button's action, you have to call yourLabelName.startBlink()Epigene
Nice solution. Works as a charmTimmy
C
23

You can simply make an extension to the UILabel class that will support the blinking effect. I don't think using a timer is a right approach since you won't have any fade effect.

Here is the Swift way to do this:

extension UILabel {
    func blink() {
        self.alpha = 0.0;
        UIView.animateWithDuration(0.8, //Time duration you want,
                            delay: 0.0,
                          options: [.CurveEaseInOut, .Autoreverse, .Repeat],
                       animations: { [weak self] in self?.alpha = 1.0 },
                       completion: { [weak self] _ in self?.alpha = 0.0 })
    }
}

Swift 3:

extension UILabel {
    func blink() {
        self.alpha = 0.0;
        UIView.animate(withDuration: 0.8, //Time duration you want,
            delay: 0.0,
            options: [.curveEaseInOut, .autoreverse, .repeat],
            animations: { [weak self] in self?.alpha = 1.0 },
            completion: { [weak self] _ in self?.alpha = 0.0 })
    }
}

EDIT Swift 3: Works for almost any view

extension UIView {
    func blink() {
        self.alpha = 0.0;
        UIView.animate(withDuration: 0.8, //Time duration you want,
            delay: 0.0,
            options: [.curveEaseInOut, .autoreverse, .repeat],
            animations: { [weak self] in self?.alpha = 1.0 },
            completion: { [weak self] _ in self?.alpha = 0.0 })
    }
}
Cutlass answered 2/3, 2016 at 20:28 Comment(1)
Did this, somehow it's not working. No error message. Just doesn't work.Sublet
S
22

Use NSTimer

NSTimer *timer = [NSTimer 
                      scheduledTimerWithTimeInterval:(NSTimeInterval)(1.0)
                            target:self 
                             selector:@selector(blink) 
                             userInfo:nil 
                             repeats:TRUE];
BOOL blinkStatus = NO;

in your blink function

-(void)blink{
   if(blinkStatus == NO){
      yourLabel.backgroundColor = [UIColor whiteColor];
     blinkStatus = YES;
   }else {
      yourLabel.backgroundColor = [UIColor grayColor];
      blinkStatus = NO;
   }
}
Spectroscopy answered 3/6, 2011 at 8:12 Comment(4)
Shouldn't you use BOOL, YES and NO rather than bool, TRUE and FALSE ? Thx.Promiscuous
@Promiscuous Yes. One of my early(nostalgic) iOS programming bad practices. Corrected now. Thanks for noting that.Spectroscopy
@Spectroscopy Speaking of bad practices. Repeating timers at 60fps... this should be an animation (there is discrete animations for when you don't want any interpolation between the values)Existence
Nice. The UIView animation example work on fading the alpha. OP wanted a BLINK effect. This does it.Insubstantial
B
6

A different approach but works. Blinking only for 3 seconds

extension UIView {
  func blink() {
    let animation = CABasicAnimation(keyPath: "opacity")
    animation.isRemovedOnCompletion = false
    animation.fromValue           = 1
    animation.toValue             = 0
    animation.duration            = 0.8
    animation.autoreverses        = true
    animation.repeatCount         = 3
    animation.beginTime           = CACurrentMediaTime() + 0.5
    self.layer.add(animation, forKey: nil)
    }
}
Benildas answered 6/1, 2018 at 10:7 Comment(0)
R
3

Rather use the view animations. It makes it very simple and is easy to control. Try this:

self.yourLabel.alpha = 1.0f;
[UIView animateWithDuration:0.12
  delay:0.0
  options:UIViewAnimationOptionCurveEaseInOut | 
          UIViewAnimationOptionRepeat | 
          UIViewAnimationOptionAutoreverse | 
          UIViewAnimationOptionAllowUserInteraction
  animations:^{
   self.yourLabel.alpha = 0.0f;
}
completion:^(BOOL finished){
// Do nothing
}];

You can tweak the values to get different effects for example, changing animateWithDuration wil set the blinking speed. Further you can use it on anything that inherits from UIView example a button, label, custom view etc.

Rivalee answered 3/6, 2014 at 8:10 Comment(0)
J
2

Tweaking Krishnabhadra Answer to give a better blink effect

Declare a Class variable bool blinkStatus;

And paste code given below

NSTimer *yourtimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(10.0 / 60.0)  target:self selector:@selector(blink) userInfo:nil repeats:TRUE];
    blinkStatus = FALSE;

-(void)blink{
    if(blinkStatus == FALSE){
        yourLabel.hidden=NO;
        blinkStatus = TRUE;
    }else {
        yourLabel.hidden=YES;
        blinkStatus = FALSE;
    }
}
Jessikajessup answered 16/7, 2013 at 15:21 Comment(2)
where should u use timer?Receptacle
hi vishnu when ever you want the label to start blinkingJessikajessup
S
2
-(void) startBlinkingLabel:(UILabel *)label 
{
    label.alpha =1.0f;
    [UIView animateWithDuration:0.32
                          delay:0.0
                        options: UIViewAnimationOptionAutoreverse |UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction |UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         label.alpha = 0.0f;
                     }
                     completion:^(BOOL finished){
                         if (finished) {

                         }
                     }];
}

-(void) stopBlinkingLabel:(UILabel *)label 
{
    // REMOVE ANIMATION
    [label.layer removeAnimationForKey:@"opacity"];
    label.alpha = 1.0f;
}
Sottish answered 25/3, 2015 at 8:0 Comment(0)
W
2

My swift version based on Flex Elektro Deimling's answer:

private func startTimeBlinkAnimation(start: Bool) {
    if start {
        timeContainerView.alpha = 1
        UIView.animateWithDuration(0.6, delay: 0.3, options:[.Repeat, .Autoreverse], animations: { _ in
            self.timeContainerView.alpha = 0
        }, completion: nil)
    }
    else {
        timeContainerView.alpha = 1
        timeContainerView.layer.removeAllAnimations()
    }
}
Weaponeer answered 26/11, 2015 at 9:51 Comment(0)
S
2

Got stuck when trying with swift and using multiple options but this seems to work nicely:

self.cursorLabel.alpha = 1
UIView.animate(withDuration: 0.7, delay: 0.0, options: [.repeat, .autoreverse, .curveEaseInOut], animations: {
    self.cursorLabel.alpha = 0
}, completion: nil)
Sailboat answered 8/1, 2016 at 20:4 Comment(0)
I
1

This is how it worked for me. I adapted the answer of @flex_elektro_deimling

First parameter UIView.animateWithDuration is the total time of the animation (In my case I've set it to 0.5), you may set different values on the first and second (delay) to change the blinking speed.

    self.YOURLABEL.alpha = 0;
    UIView.animateWithDuration(
        0.5, 
        delay: 0.2, 
        options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: {
            self.YOURLABEL.alpha = 1
        },
        completion:nil)
Ina answered 8/6, 2015 at 22:37 Comment(0)
F
0
    int count;
    NSTimer *timer;

      timer= [NSTimer
                  scheduledTimerWithTimeInterval:(NSTimeInterval)(0.5)
                  target:self
                  selector:@selector(animationStart)
                  userInfo:nil
                  repeats:TRUE];

-(void)animationStart{
switch (count) {
    case 0:
        //205   198 115
        count++;
        lbl.textColor=[UIColor colorWithRed:205.0f/255.0f green:198.0f/255.0f blue:115.0f/255.0f alpha:1];

        break;
    case 1:
         count++;
        //205   198 115 56  142 142
        lbl.textColor=[UIColor colorWithRed:56.0f/255.0f green:142.0f/255.0f blue:142.0f/255.0f alpha:1];

        break;
    case 2:
         count++;
        //205   198 115
        lbl.textColor=[UIColor colorWithRed:205.0f/255.0f green:205.0f/255.0f blue:0.0f/255.0f alpha:1];

        break;
    case 3:
         count++;
        //205   198 115 84  255 159
        lbl.textColor=[UIColor colorWithRed:84.0f/255.0f green:255.0f/255.0f blue:159.0f/255.0f alpha:1];

        break;
    case 4:
         count++;
        //205   198 115 255 193 37
        lbl.textColor=[UIColor colorWithRed:255.0f/255.0f green:193.0f/255.0f blue:37.0f/255.0f alpha:1];

        break;
    case 5:
         count++;
        //205   198 115 205 200 177
        lbl.textColor=[UIColor colorWithRed:205.0f/255.0f green:200.0f/255.0f blue:117.0f/255.0f alpha:1];

        break;
    case 6:
         count++;
        //205   198 115 255 228 181
        lbl.textColor=[UIColor colorWithRed:255.0f/255.0f green:228.0f/255.0f blue:181.0f/255.0f alpha:1];

        break;
    case 7:
         count++;
        //205   198 115 233 150 122
        lbl.textColor=[UIColor colorWithRed:233.0f/255.0f green:150.0f/255.0f blue:122.0f/255.0f alpha:1];

        break;
    case 8:
        count++;
        //205   198 115 233 150 122
        lbl.textColor=[UIColor colorWithRed:255.0f/255.0f green:200.0f/255.0f blue:200.0f/255.0f alpha:1];

        break;
    case 9:
         count=0;
        //205   198 115 255 99  71 255  48  48
        lbl.textColor=[UIColor colorWithRed:255.0f/255.0f green:48.0f/255.0f blue:48.0f/255.0f alpha:1];

        break;

    default:
        break;
}

}

Floc answered 17/10, 2014 at 8:43 Comment(0)
F
0

Here is my solution in Swift 4.0 with extension for any UIVIew

extension UIView{
    func blink() {
        self.alpha = 0.2

        UIView.animate(withDuration: 1,
                                   delay: 0.0,
                                   options: [.curveLinear,
                                             .repeat,
                                             .autoreverse],
                                   animations: { self.alpha = 1.0 },
                                   completion: nil)   
    }
}
Farnese answered 20/11, 2017 at 11:9 Comment(0)
M
0

For Swift 3+, building on all the great answers here, I ended up with a few tweaks that gave me smooth blinking effect that automatically stops after a given number of cycles.

extension UIView {
    func blink(duration: Double=0.5, repeatCount: Int=2) {
        self.alpha = 0.0;
        UIView.animate(withDuration: duration,
            delay: 0.0,
            options: [.curveEaseInOut, .autoreverse, .repeat],
            animations: { [weak self] in
                UIView.setAnimationRepeatCount(Float(repeatCount) + 0.5)
                self?.alpha = 1.0
            }
        )
    }
}
Milkman answered 30/5, 2019 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.