![](/img/trans.png)
[英]How to add an UINavigationController to an UIViewController presented as Modal
[英]How to tell if there is a modal UIViewController presented?
有沒有辦法告訴在調用dismissModalViewControllerAnimated
之前是否已經提供了模態UIViewController?
這個問題的答案太多了,沒有一個涵蓋所有案例。 此外,盡管您在文檔中找到了什么,但現在已棄用的modalViewController
有兩種替代 modalViewController
:
如果你需要知道你是不是莫代爾:
BOOL modal = nil != [self presentingViewController];
如果你需要知道你是否被模態覆蓋 :
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.