Search code examples
swiftuicollectionviewuiactivityindicatorview

Show Activity Indicator while data load in collectionView Swift


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

Solution

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