我正在尝试快速实现一个加载屏幕,我可以从项目中的任何类中重用它(我有几个类可以处理“长时间运行”的事件)
公共(public)功能是,来自另一个答案:
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()
}
通过使用在 FirstViewController.swift(它所在的位置)中工作正常:
LoadingOverlay.shared.showOverlay(self.view)
我的问题是,如何在 XYZ.swift 中使用它?因为 self.view 可能不是指该类生成的 View 。是否可以调用并找到当前的 super View ,然后在其上添加加载屏幕?
最佳答案
您需要将叠加层添加到主 UIWindow
类中。在这种情况下,您将覆盖所有 View 。
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:您可以将大部分overlayView
自定义代码移动到init
函数,因为您不需要更新backgroundColor
或其他东西每次都在展示。
PPS:有很棒的库可以像
一样加载叠加层https://github.com/TransitApp/SVProgressHUD
https://github.com/jdg/MBProgressHUD
和其他人。谷歌一下
关于ios - 从 Swift 中的任何类加载屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32682646/