user3766930
user3766930

Reputation: 5829

how can I fade in and out different texts on the same UILabel in Swift?

Currently I have an array of strings in my swift and I'm displaying them in a loop on the UILabel:

let greetings = ["Test1", "Test2", "Test3", "Test4"]

override func viewDidLoad(){
    super.viewDidLoad()
    Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(TutorialEntryPoint.update), userInfo: nil, repeats: true)
}

var i = 0
func update() {
    if(i==4){
        i=0
    }
    myLabel.text = greetings[i]
    i += 1 
}

That works, but each text disappears and shows suddenly - is there a way of modifying it so that each text disappears/shows smoothly? I thought about using animateWithDuration and modifying alpha, but I'm not sure how to do it properly.

Upvotes: 1

Views: 1960

Answers (3)

Ando
Ando

Reputation: 325

I tried several variations of this over the course of a few days, and the best solution I found was here: https://medium.com/ios-os-x-development/swift-3-so-i-wanted-to-animate-a-label-14dd2b332ef9

The variables & functions have to be changed to account for String types rather than Ints. I was using an array of strings (as in the question here), so I incremented an index after setTextValue on line 131.

Upvotes: 0

Rajat
Rajat

Reputation: 11127

You can animate setting text on label like this

UIView.transition(with: label,
                      duration: 0.25,
                      options: [.transitionCrossDissolve],
                      animations: {
                      label.text = "Your Text"
}, completion: nil)

Upvotes: 4

Fonix
Fonix

Reputation: 11597

Could try something like this

    //inside viewDidLoad
    let animation = CAKeyframeAnimation()
    animation.keyPath = "opacity"
    animation.values = [0, 1, 1, 0]
    animation.keyTimes = [0, 0.1, 0.9, 1]
    animation.duration = 2.0 //same as your timer
    animation.repeatCount = Float.infinity

    myLabel.layer.addAnimation(animation, forKey: "fade")

haven't tested it, so may need some tweaking, but ive used something like this to fade something in and out before

Upvotes: 1

Related Questions