Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding & Removing A View Overlay in Swift

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()          
})
like image 551
Colin Avatar asked Feb 08 '23 20:02

Colin


1 Answers

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()
}
like image 68
Mate Hegedus Avatar answered Feb 16 '23 18:02

Mate Hegedus