在 collectionView Swift 中加载数据时显示 Activity 指示器

Show Activity Indicator while data load in collectionView Swift

我如何在加载 collectionView 中的数据时显示 activity 指示器和白色背景?

我目前有这个:

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

试试这个,希望对你有帮助

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