在Swift中加载指标

时间:2015-03-10 08:43:18

标签: swift xcode6

如何在视图控制器中显示加载指示器。

我在viewDidLoad()中使用Alamofire。

    Alamofire.request(.GET, formURL, parameters: nil)
        .responseJSON { (request, response, jsonResult, error) in


            }

1 个答案:

答案 0 :(得分:8)

有多种方法可以做到这一点,但如果你在视图控制器中调用Alamofire,你可以将这些属性添加到类中:

var spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
var loadingView: UIView = UIView()

添加两个帮助程序,您应该自定义适合您应用程序的任何内容:

func showActivityIndicator() {
    dispatch_async(dispatch_get_main_queue()) {
        self.loadingView = UIView()
        self.loadingView.frame = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
        self.loadingView.center = self.view.center
        self.loadingView.backgroundColor = UIColor(rgba: "#444444")
        self.loadingView.alpha = 0.7
        self.loadingView.clipsToBounds = true
        self.loadingView.layer.cornerRadius = 10

        self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
        self.spinner.frame = CGRect(x: 0.0, y: 0.0, width: 80.0, height: 80.0)
        self.spinner.center = CGPoint(x:self.loadingView.bounds.size.width / 2, y:self.loadingView.bounds.size.height / 2)

        self.loadingView.addSubview(self.spinner)
        self.view.addSubview(self.loadingView)
        self.spinner.startAnimating()
    }
}

func hideActivityIndicator() {
    dispatch_async(dispatch_get_main_queue()) {
        self.spinner.stopAnimating()
        self.loadingView.removeFromSuperview()
    }
}

并在需要时调用它,例如:

showActivityIndicator()
Alamofire.request(.GET, formURL, parameters: nil)
        .responseJSON { (request, response, jsonResult, error) in
             self.hideActivityIndicator()

            }