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

时间:2017-10-09 15:38:44

标签: swift uicollectionview uiactivityindicatorview

如果我的collectionView中的数据加载,我将如何显示活动指示符和白色背景?

我目前有这个:

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

1 个答案:

答案 0 :(得分:1)

试试这个我希望这会对你有所帮助

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