关注此问题:Loading Screen from any Class in 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()
})
答案 0 :(得分:6)
Swift 2
您是否从后台线程调用hideOverlayView()
?如果你是,你应该确保它在主线程上运行:
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()
}