Search code examples
iosswiftlabelfade

Fading an array of strings in and out


Using swift i am able to get the words "Hello, World" to fade in and out every 2 seconds with a 3 second delay.

What is the best way to get multiple strings (5-8) to fade in and out repeatedly one at a time?

Thanks!


Solution

  • You need a pair of nested animations, one to handle the fade in and the other to handle the fade out. You can call the second in the completion block of the first.

    Then you need to change the message and then animate the new message, which is simply calling the animation pair again. Here is one way:

    class ViewController: UIViewController {
    
        @IBOutlet weak var label: UILabel!
    
        let theMessages=["Message 1","Message 2","The third message","The final message"]
        var messageIndex=0;
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            self.label.text=""
            self.label.alpha=0;
            self.animateMessage()
        }
    
        func animateMessage() {
            self.label.text=self.theMessages[self.messageIndex];
            if (++self.messageIndex == self.theMessages.count) {
                self.messageIndex=0;
            }
    
            UIView.animateWithDuration(2.0, delay: 0.5, options: .CurveEaseInOut, animations: { () -> Void in
                self.label.alpha=1.0
                }, completion: { (success) -> Void in
                    UIView.animateWithDuration(2.0, delay: 0.5, options: .CurveEaseInOut, animations: { () -> Void in
                        self.label.alpha=0
                        }, completion: { (success) -> Void in
                            self.animateMessage()
                    })
            })
        }
    }