Cannot display UIActivityIndicatorView

76 Views Asked by At

I meet a question. I am using following code to display UIActivityIndicatorView. My requirement is to be able to create an UIActivityIndicatorView and display it when I click the button with tag 1, if I click other buttons the UIActivityIndicatorView will be removed from the super view.

class ViewController: UIViewController {
 lazy var acLoad:(UIActivityIndicatorView) = {
        let myActivityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.white)
        myActivityIndicator.center = view.center
        myActivityIndicator.hidesWhenStopped = true
        myActivityIndicator.startAnimating()
        return myActivityIndicator
    }()
    //more code
    @objc func btnAction(sender: UIButton){
        switch sender.tag {
        case 1:
            print("created")
            view.addSubview(acLoad)
            acLoad.startAnimating()
        default:
            print("removed")
            acLoad.stopAnimating()
            acLoad.removeFromSuperview()
        }
    }
}

The above doesn't work, I can get the print log after click, but UIActivityIndicatorView doesn't display, any ideas?

1

There are 1 best solutions below

0
Tarun Tyagi On

It seems like your UIActivityIndicatorView might be misplaced (wrong frame value) - so it is not visible to you.

print("created")
view.addSubview(acLoad)
acLoad.startAnimating()

// Add this line in your button tap code
// It will tell you where it is placed inside your view
print(acLoad.frame)

If you find that it's frame is not where you want it to be, just fix your layout code and it will be where you expect it to be.

Another note - myActivityIndicator.hidesWhenStopped = true makes it automatically hide on stopAnimating() call. So you can add it only once, not remove-add every time.

Also check your view.backgroundColor vs acLoad style.