2015-10-11 58 views
0

從這個問題下面:Loading Screen from any Class in Swift添加和刪除一個視圖疊加在斯威夫特

問題:加載覆蓋視圖將顯示,但是當hideOverlayView()被調用時不會隱藏。在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:奇怪然而,覆蓋了一些時間(將出現15到30秒後)

代碼後消失如:

LoadingOverlay.shared.showOverlay() 

解決方案:

我在調用後臺線程。根據下面的答案,請致電:

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

回答

4

您是否從後臺線程調用hideOverlayView()?如果你是,你應該確保它在主線上運行:

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

絕對完美。謝謝! – Colin