首页 > 解决方案 > iOS - 当视图控制器以模态方式呈现时,如何将视图保持在前面?

问题描述

TestView我有一个导航 ViewController,当用户关闭互联网时,我想添加一个在所有 ViewControllers 上命名的自定义视图。当 Internet 连接状态发生变化时,我将自定义视图添加到 keyWindow。当我推送 ViewController 时,视图会显示并停留在那里,但是当我以模态方式呈现 ViewController 时,模态 ViewController 会覆盖视图。

即使以模态方式呈现 VC,我也希望视图保持在最前面,并且我希望能够在我的 AppDelegate 文件中为所有模态 ViewControllers 或类似的东西添加一些代码。我怎样才能在 swift 5 中做到这一点?我在想如果每次呈现模态 VC 时都会触发一个函数,我可以在那里添加我的代码。这是我的 AppDelegate 目前的样子:


class AppDelegate: UIResponder, UIApplicationDelegate, ReachabilityObserverDelegate   {
    var reachability: Reachability?
    var window: UIWindow?
    var internetView: TestView?

    //This is called when the internet connects or disconnects
    func reachabilityChanged(_ isReachable: Bool) { 
        window = getKEYWindow()
        if !isReachable {
            window?.addSubview(internetView!)
        }
        else {
            internetView?.removeFromSuperview()
        }
    }

    func getKEYWindow() -> UIWindow? {
        return UIApplication.shared.connectedScenes.filter({$0.activationState == .foregroundActive}).map({$0 as? UIWindowScene}).compactMap({$0}).first?.windows.filter({$0.isKeyWindow}).first
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        try? addReachabilityObserver()
        internetView = TestView(frame: CGRect(x:0, y: 50, width: UIScreen.main.bounds.size.width, height: 14))
        return true
    }

}

主视图控制器:

互联网关闭:

推送视图控制器:

以模态方式呈现 ViewController:


更新:我找到了另一种保持视野领先的方法。我添加了以下行internetView.layer.zPosition = .greatestFiniteMagnitudedidFinishLaunchingWithOptions它就像一个魅力。谢谢大家的帮助。

标签: iosswiftxibmodalviewcontrollerpresentmodalviewcontroller

解决方案


我可以建议一种方法:

打开更高级别的新 UIWindow 并将其绘制在整个应用程序之上。

我不知道这是否是最好的方法,但是我只是在一个空的应用程序上使用以下代码对其进行了测试——它似乎有效——甚至可以是透明的。

 _myWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; 
 [_myWindow makeKeyAndVisible];

 UIViewController* dummyVC = [[UIViewController alloc] init];
 dummyVC.view = [[UIView alloc]initWithFrame:_myWindow.bounds];
 [dummyVC.view setOpaque:NO]; 
 [dummyVC.view setAlpha:0.1f];

 [_myWindow setRootViewController:dummyVC];
 _myWindow.windowLevel = UIWindowLevelAlert + 1;

 [_myWindow.rootViewController.view.layer setBackgroundColor:[UIColor greenColor].CGColor]; 

推荐阅读