I actually created an extension to UIView. So that I just do this with the ViewController's first view:
view.displayBusy() // you don't need 'self.view' in Swift
...
view.displayNotBusy()
I also tried this:
view.displayBusy()
DispatchQueue.global().async {
doSomething()
DispatchQueue.main.async {
doSomethingComplete()
}
}
func doSomethingComplete() {
view.displayNotBusy()
}
Not working either.
And here's my extension. I add the subview, I bring it to the front. But I cannot see it. I also set breakpoints and checked out the frame after the constraints were updated. It is right in the center. And I've tested without the 'displayNotBusy', and with 'hidesWhenStopped' set to false just to make sure it didn't jump right thru the busy area. I made the size 128.
I cannot see it. Does anyone know why I don't see it?
extension UIView {
func displayBusy() {
var busyView : UIActivityIndicatorView? = viewWithTag(0x4255) as? UIActivityIndicatorView
if busyView == nil {
busyView = UIActivityIndicatorView(frame: CGRect(x: 50, y: 50, width: 32, height: 32))
busyView!.tag = 0x4255
addSubview(busyView!)
busyView!.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(item: busyView!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 32)
let heightConstraint = NSLayoutConstraint(item: busyView!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 32)
addConstraints([widthConstraint, heightConstraint])
let horConstraint = NSLayoutConstraint(item: busyView!, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)
let verConstraint = NSLayoutConstraint(item: busyView!, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
addConstraints([horConstraint, verConstraint])
// Now make it all happen
setNeedsUpdateConstraints()
setNeedsLayout()
layoutIfNeeded()
}
self.bringSubview(toFront: busyView!)
busyView!.hidesWhenStopped = true
busyView!.isHidden = false
busyView!.startAnimating()
}
func displayNotBusy() {
let busyView : UIActivityIndicatorView? = viewWithTag(0x4255) as? UIActivityIndicatorView
if busyView != nil {
busyView!.stopAnimating()
}
}
}