iosswiftuilabelswift3animatewithduration

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.


Solution

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