Adding & Removing A View Overlay in Swift
Asked Answered
F

1

5

Following from this question: Loading Screen from any Class in Swift

Issue: The loading overlay view will display but will not hide when hideOverlayView() is called. Oddly however, the overlay disappears after some time (15 to 30 seconds after it appears)

Code: Contained in FirstController.swift

public class LoadingOverlay{

var overlayView = UIView()
var activityIndicator = UIActivityIndicatorView()

class var shared: LoadingOverlay {
    struct Static {
        static let instance: LoadingOverlay = LoadingOverlay()
    }
    return Static.instance
}

public func showOverlay() {
    if  let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate,
        let window = appDelegate.window {
            overlayView.frame = CGRectMake(0, 0, 80, 80)
            overlayView.center = CGPointMake(window.frame.width / 2.0, window.frame.height / 2.0)
            overlayView.backgroundColor = MyGlobalVariables.UICOLORGREEN
            overlayView.clipsToBounds = true
            overlayView.layer.cornerRadius = 10

            activityIndicator.frame = CGRectMake(0, 0, 40, 40)
            activityIndicator.activityIndicatorViewStyle = .WhiteLarge
            activityIndicator.center = CGPointMake(overlayView.bounds.width / 2, overlayView.bounds.height / 2)

            overlayView.addSubview(activityIndicator)
            window.addSubview(overlayView)

            activityIndicator.startAnimating()
    }
}

public func hideOverlayView() {
    activityIndicator.stopAnimating()
    overlayView.removeFromSuperview()
}
}

And called in functions in DataManager.swift as:

LoadingOverlay.shared.showOverlay()

Solution:

I was calling on a background thread. As per the answers below, call as:

dispatch_async(dispatch_get_main_queue(), { // This makes the code run on the main thread
  LoadingOverlay.shared.hideOverlayView()          
})
Florentinaflorentine answered 11/10, 2015 at 12:25 Comment(0)
V
9

Swift 2

Are you calling hideOverlayView() from a background thread? If you are, you should make sure it runs on the main thread:

dispatch_async(dispatch_get_main_queue(), { // This makes the code run on the main thread
  LoadingOverlay.shared.hideOverlayView()          
})

Swift 3+

DispatchQueue.main.async {
  LoadingOverlay.shared.hideOverlayView()
}
Vortex answered 11/10, 2015 at 12:28 Comment(1)
Absolutely perfect. Thank you!Florentinaflorentine

© 2022 - 2024 — McMap. All rights reserved.