Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a label fade in or out in swift

I am looking to make a label fade in, in viewDidLoad(), and then after a timer is at 3 fade out. I am not familiar with the fadein or fadeout functions.

How would I go about doing this?

like image 791
Ty Victorson Avatar asked Feb 13 '16 22:02

Ty Victorson


1 Answers

Even though the view has loaded, it may not be visible to the user when viewDidLoad is called. This means you might find your animations appears to have already started when you witness it. To overcome this issue, you'll want to start your animation in viewDidAppear instead.

As for the fadeIn and fadeOut functions - they don't exist. You'll need to write them yourself. Thankfully, it's very easy to do this. Something like the below might be good enough.

func fadeViewInThenOut(view : UIView, delay: NSTimeInterval) {

    let animationDuration = 0.25

    // Fade in the view
    UIView.animateWithDuration(animationDuration, animations: { () -> Void in
        view.alpha = 1
        }) { (Bool) -> Void in

            // After the animation completes, fade out the view after a delay

            UIView.animateWithDuration(animationDuration, delay: delay, options: .CurveEaseInOut, animations: { () -> Void in
                view.alpha = 0
                },
                completion: nil)
    }
}
like image 55
Andy Avatar answered Sep 20 '22 16:09

Andy