开发者

How to find root UIViewController

I have a view that is UIViewController (root) that handles ads and a UINavigationController. In that UINavigationController I have typical layers of controllers. In my custom settings table view controller, I have a button to contact me for support. When the user clicks this button I create a MFMailComposeViewController and would like to present it. I can't present it from the settings table view as it will be underneath my ads, so I need to reference the root view and present it from there. I've tried self.parentViewController.parentViewController where self is the settings tab开发者_如何学Cle view, but that doesn't work. How should I reference this. It seems like a bad design to have to reference the root view directly and pass it to the settings view.


Get the current keyWindow:

UIWindow *window = [UIApplication sharedApplication].keyWindow;

Get its rootViewController:

UIViewController *rootViewController = window.rootViewController;

NOTE: If an UIAlertView is currently being shown, a new window is being created and assigned to be the keyWindow. There might be other exceptional cases as well that will not keep your application window to be the keyWindow.


In my experience, this is the ideal solution to get the rootViewController:

[[[[UIApplication sharedApplication] delegate] window] rootViewController]

Note: In-case of an active UIAlert or UIActionSheet, you get the Alert or Action Sheet as your key window.


Use the app singleton. Something like:

[[[UIApplication sharedApplication] delegate] rootViewController] should get it if your viewController that is the root is named rootViewController


You can always solve this with 1 line of code but I recommend this Swift way to do it, you can call this from anywhere, its also crash and bug safe:

/// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups
var topMostVC: UIViewController? {
    var presentedVC = UIApplication.sharedApplication().keyWindow?.rootViewController
    while let pVC = presentedVC?.presentedViewController {
        presentedVC = pVC
    }

    if presentedVC == nil {
        print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
    }
    return presentedVC
}

Its included as a standard function in:

https://github.com/goktugyil/EZSwiftExtensions


Get the UIApplication object. Cycle through the windows array to find the keyWindow. And then get the rootViewController property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜