Loading Screen from any Class in Swift

2019-06-05 08:37发布

问题:

I am trying to implement a loading screen in swift, that I can reuse from any class in the project (I have a few classes that will handle 'long running' activities)

The public function is, from another answer:

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(view: UIView) {

    overlayView.frame = CGRectMake(0, 0, 80, 80)
    overlayView.center = view.center
    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)
    view.addSubview(overlayView)

    activityIndicator.startAnimating()
}

public func hideOverlayView() {
    activityIndicator.stopAnimating()
    overlayView.removeFromSuperview()
}

}

Which works fine in FirstViewController.swift (Where it is located) by using:

LoadingOverlay.shared.showOverlay(self.view)

My question is, how do I use it in XYZ.swift? As self.view may not be referring to a view generated by that class. Is it possible to call and find the current super view, then add the loading screen on top of it?

回答1:

You need to add your overlay to your main UIWindow class. In that case you will overlay all views.

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

PS: you can move most of overlayView customization code to init function, because you don't need to update backgroundColor or other things every time on display.

PPS: There is great libraries for loading overlay like

https://github.com/TransitApp/SVProgressHUD

https://github.com/jdg/MBProgressHUD

and others. Just google it