活动指示器在执行时未显示

时间:2015-10-08 22:29:53

标签: ios swift uiactivityindicatorview

我正在尝试在用户点击登录按钮时显示活动指示符。如果我将startActivityIndicator()代码放在viewDidLoad()中,它会在屏幕上完全按预期显示。当我作为btnSignIn()中的第一步执行它时,它永远不会出现。有点失落,所以我希望Stack大师可以帮忙...

// Here are the variable declarations
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
var loadingView: UIView = UIView()
var viewCenter:CGPoint!

@IBAction func btnSignIn(sender: AnyObject) {

    startActivityIndicator()

    if validateEmailAddress(txtEmailAddress.text!) == false {
        stopActivityIndicator(self.loadingView)
        return
    }

    if validatePassword(txtPassword.text!) == false {
        stopActivityIndicator(self.loadingView)
        return
    }

    PFUser.logInWithUsernameInBackground(txtEmailAddress.text!, password:txtPassword.text!) {
        (user: PFUser?, error: NSError?) -> Void in
        if user != nil {

            // Successful login.
            self.txtPassword.resignFirstResponder()
            self.txtEmailAddress.resignFirstResponder()

            self.getUserInfo()

        } else {
            self.stopActivityIndicator(self.loadingView)
            // The login failed. Display alert.
            self.displayAlert("Whoops!", message: "Email or Password are incorrect.")
        }
    }
}

func startActivityIndicator() {

    loadingView.frame = CGRectMake(0, 0, 80, 80)
    loadingView.center = viewCenter
    print(viewCenter)
    loadingView.backgroundColor = UIColorFromRGB("444444", alpha: 0.7)
    loadingView.clipsToBounds = true
    loadingView.layer.cornerRadius = 10

    activityIndicator.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
    activityIndicator.center = CGPointMake(loadingView.frame.size.width / 2, loadingView.frame.size.height / 2);

    view.addSubview(loadingView)
    loadingView.addSubview(activityIndicator)

    UIApplication.sharedApplication().beginIgnoringInteractionEvents()

    activityIndicator.startAnimating()

}

func stopActivityIndicator(uiView: UIView) {

    activityIndicator.stopAnimating()
    loadingView.removeFromSuperview()
    UIApplication.sharedApplication().endIgnoringInteractionEvents()
}

1 个答案:

答案 0 :(得分:2)

使用我的delay实用程序(请参阅此处:https://stackoverflow.com/a/24318861/341994),重写如下:

@IBAction func btnSignIn(sender: AnyObject) {
    startActivityIndicator()
    delay(0.1) {
        if validateEmailAddress(txtEmailAddress.text!) == false {
        // ... everything else goes here ...
    }
}

延迟使活动指示器有机会出现并开始旋转。