Adding & Removing A View Overlay in Swift

ぃ、小莉子 提交于 2019-11-30 13:33:14

问题


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()          
})

回答1:


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()
}


来源:https://stackoverflow.com/questions/33064908/adding-removing-a-view-overlay-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!