4

How would I go about showing an activity Indicator and a white background while the data in my collectionView loads?

I currently have this:

let activityView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)
    self.view.addSubview(activityView)
    activityView.hidesWhenStopped = true
    activityView.center = self.view.center
    activityView.startAnimating()

    DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async {
        fetchPosts()
    }

    DispatchQueue.main.async {
        UIView.animate(withDuration: 1, delay: 1, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
            self.collectionView?.reloadData()
            self.collectionView?.alpha = 1
            self.activityView.stopAnimating()
        }, completion: nil)
    }
}
ayjoy
  • 155
  • 3
  • 10
  • You can change the [`color`](https://developer.apple.com/documentation/uikit/uiactivityindicatorview/1622836-color) of the `UIActivityInidicatorView` to something other than white. – Paolo Oct 09 '17 at 15:41

1 Answers1

4

Try this i hope this will help you

let activityView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)

override func viewDidAppear(_ animated: Bool) {

   super.viewDidAppear(animated)

    let fadeView:UIView = UIView()
    fadeView.frame = self.view.frame
    fadeView.backgroundColor = UIColor.whiteColor()
    fadeView.alpha = 0.4

    self.view.addSubview(fadeView)

    self.view.addSubview(activityView)
    activityView.hidesWhenStopped = true
    activityView.center = self.view.center
    activityView.startAnimating()

   DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async {
    fetchPosts()
   }

   DispatchQueue.main.async {
    UIView.animate(withDuration: 1, delay: 1, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
        self.collectionView?.reloadData()
        self.collectionView?.alpha = 1
        fadeView.removeFromSuperview()
        self.activityView.stopAnimating()
    }, completion: nil)
 }
}
Zee
  • 327
  • 1
  • 8
  • it really helped me! – Alexey Oct 17 '18 at 04:00
  • Instead of arbitrarily waiting for one second before animating in the collection view, you probably should use a closure in `fetchPosts` and execute the animation then. Otherwise it is not guaranteed that the posts are there before the collection view is shown. – Julian Vogels Aug 12 '20 at 08:26