Activity indicator not showing when executed

2020-03-31 07:01发布

问题:

I am trying to display an activity indicator when the user hits the login button. If I put the startActivityIndicator() code in viewDidLoad() it shows on the screen exactly as expected. When I execute it as the first step in btnSignIn() it never appears. A little lost, so i'm hoping the Stack guru's can help...

// 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:

Using my delay utility (see here: https://stackoverflow.com/a/24318861/341994), rewrite like this:

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

The delay gives the activity indicator a chance to appear and start spinning.