繁体   English   中英

如何判断是否存在模态UIViewController?

[英]How to tell if there is a modal UIViewController presented?

有没有办法告诉在调用dismissModalViewControllerAnimated之前是否已经提供了模态UIViewController?

iOS 9,8,7,6和5

这个问题的答案太多了,没有一个涵盖所有案例。 此外,尽管您在文档中找到了什么,但现在已弃用的modalViewController两种替代 modalViewController

  1. 如果你需要知道是不是莫代尔:

    BOOL modal = nil != [self presentingViewController];

  2. 如果你需要知道你是否模态覆盖

    BOOL hiddenByModal = nil != [self presentedViewController];

iOS6的+ -使用presentedViewController:由于iOS 6的, presentedViewController应当代替用作modalViewController已弃用

使用该属性:

不推荐使用 - modalViewController:活动模态视图的控制器 - 即临时显示在接收器管理的视图顶部的视图。 (只读)

@property(nonatomic, readonly) UIViewController *modalViewController

在iOS 5之后你应该使用:

if (self.presentingViewController != nil) {

     [self dismissViewControllerAnimated:YES completion:^{

    //has dismissViewControllerAnimated
    }];
}

编辑改变iOS版本

我通常添加一个名为isModal的BOOL变量,并在初始化一个viewcontroller之后但在调用presentModalViewController之前设置它。 就像是:

MyViewController *controller = [[MyViewController alloc] init];
controller.isModal = YES;
[self presentModalViewController:controller animated:YES];

然后,在MyViewController中,在需要解雇之前,我只检查:

if (isModal) { //dismiss modal }

我知道这已经有一段时间但只是想要加上我的2美分来解决这个问题。

当应用程序进入后台以便首先解除它时,我需要确定是否存在模态呈现的ViewController。

首先,我对UIWindow进行了扩展,以返回当前的ViewController

extension UIWindow {

    func getCurrentViewController() -> UIViewController? {

        guard let rvc = self.rootViewController else {
            return nil
        }

        if let pvc = rvc.presentedViewController {

            return pvc

        } else if let svc = rvc as? UISplitViewController, svc.viewControllers.count > 0 {

            return svc.viewControllers.last!

        } else if let nc = rvc as? UINavigationController, nc.viewControllers.count > 0 {

            return nc.topViewController!

        } else if let tbc = rvc as? UITabBarController {

            if let svc = tbc.selectedViewController {

                return svc
            }
        }

        return rvc
    }
}

然后我进入appDelegate并在applicationDidEnterBackground()上添加了一个测试:

func applicationDidEnterBackground(_ application: UIApplication) {

    if let vc = self.window?.getCurrentViewController() {

        if vc.presentingViewController != nil {

            vc.dismiss(animated: false, completion: nil)
        }
    }
}

这个解决方案是在Swift 3中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM