user3900721
user3900721

Reputation:

swift UIActivityIndicatorView .hidden = false not working

I am trying to show an Activity Indicator View once a button is pressed, but it does not want to show. If I don't set it to hidden at all, it shows, and when I try hide it, it hides. But if it is hidden, it will not show again.

Here is the code:

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    loading.hidden = true
}

@IBAction func submit() {
    loading.hidden = false
    loading.startAnimating()
    if chosenCategory == "" || txtName.text == "" || txtEmail.text == ""    {
        loading.stopAnimating()
        loading.hidden = true
    } else {
        println("animation")

No matter what, the stop animation works, and it can hide, but no matter what I do, it just seems to skip the loading.hidden = false and goes straight to printing the message out.

What could be happening?

Upvotes: 6

Views: 13357

Answers (2)

Dan Ross
Dan Ross

Reputation: 831

I would recommend not using the .hidden property at all. Use the .hidesWhenStopped property instead and set it to true. Then simply invoke the .startAnimating() method and the UIActivityIndicatorView will automatically become visible and will be animating. Invoke the .stopAnimating() method and the UIActivityIndicatorView will automatically hide.

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    loading.hidesWhenStopped = true //this is all you need to change
}

@IBAction func submit() {
    loading.startAnimating() // becomes visible
    if chosenCategory == "" || txtName.text == "" || txtEmail.text == ""    {
        loading.stopAnimating() // goes into hiding
    } else {
        println("animation")

Upvotes: 18

zisoft
zisoft

Reputation: 23078

Use the GCD (Grand Central Dispatch) routines:

    self.activityIndicator.startAnimating()
    self.activityIndicator.hidden = false

    dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), { ()->() in
        ... // your long running code here

        self.activityIndicator.stopAnimating()
    })

Upvotes: 6

Related Questions