在Swift中添加和删除一个视图覆盖
从这个问题之后: 从Swift中的任何类加载屏幕
问题 :调用hideOverlayView()时,加载覆盖视图将显示但不会隐藏。 然而奇怪的是,覆盖在一段时间后消失(出现15到30秒后)
代码 :包含在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() } }
并在DataManager.swift函数中调用如下:
LoadingOverlay.shared.showOverlay()
解:
我正在调用一个后台线程。 根据下面的答案,请拨打电话:
dispatch_async(dispatch_get_main_queue(), { // This makes the code run on the main thread LoadingOverlay.shared.hideOverlayView() })
你是从后台线程调用hideOverlayView()
吗? 如果你是,你应该确保它在主线上运行:
dispatch_async(dispatch_get_main_queue(), { // This makes the code run on the main thread LoadingOverlay.shared.hideOverlayView() })