Replacing a View with a UIActivityIndicator Programatically

80 Views Asked by At

I have been trying to create a quick method that will allow me to replace any UIView with a spinner right before a process starts and do the re-show the view once my process is done. For some reason, the UIView does disappear but the spinner never shows. These are the methods in question:

func showLoader(view: UIView, controller: UIViewController) -> UIActivityIndicatorView {

    let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    spinner.color = AC_BLUE
    spinner.center = view.center
    spinner.startAnimating()

    view.alpha = 0
    controller.view.addSubview(spinner)

    return spinner
}

func hideLoader(view: UIView, spinner: UIActivityIndicatorView) {

    view.alpha = 1
    spinner.removeFromSuperview()

}

..which I call with something like this:

let spinner = Extensions().showLoader(view: signInBtn, controller: self)

APICalls().getUser(email: usernameTextField.text!, pass: passwordTextField.text!) { success, user in

     //..CODE..//
     Extensions().hideLoader(view: self.signInBtn, spinner: spinner)

}

Also, I tried centering on the main VC view, and that does work. So I'm guessing it must be related to the view's position.

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

Try setting this before adding the spinner to the controllers view (instead of the old spinner.center = view.center):

spinner.center = view.superview!.convert(view.center, to: controller.view)

You need to convert the view's center to the coordinates of the controller.view.