在调用 dismissModalViewControllerAnimated
方法之前,有没有一种方法可以判断当前是否已经有模态视图控制器被呈现?
在调用 dismissModalViewControllerAnimated
方法之前,有没有一种方法可以判断当前是否已经有模态视图控制器被呈现?
对于这个问题,已经有太多的答案了,但并不能覆盖所有情况。 此外,尽管在文档中提到的是不建议使用的 modalViewController
,但现在有两种可供替代的方式:
如果你需要知道你自己是否是模态的:
BOOL modal = nil != [self presentingViewController];
如果你需要知道你是否被模态所遮盖:
BOOL hiddenByModal = nil != [self presentedViewController];
presentedViewController
属性作为已弃用的modalViewController
的替代品。使用以下属性:
已弃用 - modalViewController: 活动模态视图的控制器——即暂时显示在接收方管理的视图之上的视图。(只读)
@property(nonatomic, readonly) UIViewController *modalViewController
我通常会添加一个名为isModal
的BOOL变量,并在初始化视图控制器后但在调用presentModalViewController
之前设置它。例如:
MyViewController *controller = [[MyViewController alloc] init];
controller.isModal = YES;
[self presentModalViewController:controller animated:YES];
然后,在MyViewController中,在需要dismiss之前,我只需进行检查:
if (isModal) { //dismiss modal }
iOS 5 及以上版本应使用:
if (self.presentingViewController != nil) {
[self dismissViewControllerAnimated:YES completion:^{
//has dismissViewControllerAnimated
}];
}
修改 iOS 版本
我知道这已经过了一段时间,但只是想在这个问题上提供我的意见。
当应用进入后台时,我需要确定是否有以模态方式呈现的 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)
}
}
}