Kirk Ouimet Kirk Ouimet - 7 months ago 21
Swift Question

How to fade in and out an ActivityIndicator in Swift?

Here is my activity indicator:

self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
self.activityIndicator.center = self.view.center
self.view.addSubview(activityIndicator)


I can start it with
self.activityIndicator.startAnimating()
and stop it with
self.activityIndicator.stopAnimating()
. I'd like the transition when it stops to be more fluid and think it would nice to fade out the element over 400 milliseconds rather than just hiding it when I call stopAnimating.

Any ideas on how to do this?

Answer
    // Set initial state
    self.activityIndicator.alpha = 0.0

    // To show
    self.activityIndicator.startAnimating()
    UIView.animateWithDuration(0.4) {
        self.activityIndicator.alpha = 1.0
    }

    // To hide
    UIView.animateWithDuration(0.4, animations: {
        self.activityIndicator.alpha = 0.0
    }) { complete in
        self.activityIndicator.stopAnimating()
    }
Comments