Swift Recipe

How to add blink or flash effect on UIView


Animations are the important part for your app. As someone once said, make everything fancy! In this quick article, learn how to add blink or flash effect on UIView.

To add blink or flash effect on almost any view, we can simply create an extension of UIView.

extension UIView {
    func blink() {
        self.alpha = 0.0;
        UIView.animate(withDuration: 0.5, //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 })
    }
}

Let’s quickly go through what we did here.

The core logic is to change the alpha of the view to make it look like the view is fading out and then fading in, continuously.

Hence we change the alpha of the view from 0 to 1 in our animation block.

On completion of one cylce of the animation we set it back from 1 to 0.

Now that to do this continuously, we add the animation option .repeat. It will make the animation run on a repeat mode.

Adding the option .autoreverse makes it look the view is fading in and then fading out, i.e. the view is blinking!

And the option .curveEaseInOut just adds the final animation touches.

You can tweak the above function based on your requirements.

You can use this extension on almost any View for blink effect:

myLabel.blink() // Blinks your label
myView.blink() //Blinks your UIView

If you want to remove the blink effect, just update your UIView extension as:

extension UIView {
    func blink() {
        self.alpha = 0.0;
        UIView.animate(withDuration: 0.5, //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 })
    }

    func stopBlink() {
        layer.removeAllAnimations()
        alpha = 1
    }
}

Call myView.stopBlink() to stop your view from blinking.

See example usage below:

how to add blink or flash effect on UIView
Blinking view

Did you realise how easy it is to use? That’s all on how to add blink or flash effect on UIView. Go use it on your view and make it look fancy!


Learn how to add animations to your SwiftUi app here!

Checkout another quick article on How To Add Splash Screen in SwiftUI.

If you want to learn how to use SwiftUI in your existing app, then you can read it here!

or If you want to learn how to use and convert your UIViewControllers in SwiftUI, then you can read it here!


Like it? Share with your friends!

0 Comments

Your email address will not be published. Required fields are marked *