Christian DiClemente
Christian DiClemente

Reputation: 43

Make label text "blink" or "flash" on separate button press in Swift 3

Given an app with an on-screen text label and a button. Every time the button is pressed, the text changes. I want to be able to press the button and the text will "blink" when changing text, to make the text change more apparent to the user.

Given the following variables:

@IBOutlet weak var text: UILabel!
@IBAction func buttons(_ sender: UIButton) {}

I've tried SKAction, fadein/fadeout but all tutorials/help are in older versions of Swift and aren't working for me.

Upvotes: 2

Views: 6570

Answers (2)

Erik Peruzzi
Erik Peruzzi

Reputation: 535

As I posted already here: https://stackoverflow.com/a/46493987/1836369

You can extend the class UIView like this:

 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)
     }
}

In this way you can simply call

text.blink() 

to make your label blink

Upvotes: 5

Rajamohan S
Rajamohan S

Reputation: 7269

Swift 3.0
One of the method to blink of UIView is achieved by UIKit animations.

@IBOutlet var label: UILabel!

var x = 0
let text = ["Vanakkam","Hello","Hi","Hola","Ni Hao","Oi","Namastae"]

@IBAction func buttonAction(_ sender: UIButton) {

    UIView.animate(withDuration: 0.2, animations: { 
        self.label.alpha = 0.0
        }) { (bool) in
            self.label.alpha = 1.0
            self.label.text = text[self.x]
            if self.x < text.count{
                self.x = self.x+1
            }else{
                self.x = 0
            }
    }
}

OUTPUT:- enter image description here

Upvotes: 3

Related Questions