【问题标题】:iOS - How can I keep a view at front when a viewcontroller is presented modally?iOS - 当视图控制器以模态方式呈现时,如何将视图保持在前面?
【发布时间】:2020-04-14 13:05:06
【问题描述】:

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

即使 VC 以模态方式呈现,我也希望视图保持在最前面,并且我希望能够在我的 AppDelegate 文件中为所有模态 ViewController 或类似的东西添加一些代码。我怎样才能在 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
    }

}

Main ViewController:

Internet Turned Off:

Push ViewController:

Present ViewController Modally:


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

【问题讨论】:

  • 您是如何呈现视图控制器、故事板或代码的?
  • 我会尝试创建一个具有几乎最大窗口级别的新 UIWindow 并使其成为关键且可见 - 它应该位于主窗口的顶部 :-| (只是一个想法的长镜头)。

标签: ios swift xib modalviewcontroller presentmodalviewcontroller


【解决方案1】:

我可以建议一种方法:

打开更高级别的新 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]; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2020-11-24
    • 2016-02-03
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多