Finding the rootViewController in iOS

后端 未结 3 1927
北荒
北荒 2021-02-14 07:31

In ShareKit, the code needs to determine where the rootViewController is so it can show a modal view. For some reason, the code is failing in iOS 5:

    // Try t         


        
相关标签:
3条回答
  • 2021-02-14 07:42

    I'm not sure if you can rely on window.rootViewController b/c you don't have to set it. You can just add a subview to the window. The following seemed to work fine:

    id rootVC = [[[[[UIApplication sharedApplication] keyWindow] subviews] objectAtIndex:0] nextResponder];
    
    0 讨论(0)
  • 2021-02-14 08:04

    Swift way to do it, you can call this from anywhere:

    /// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups
    public 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

    0 讨论(0)
  • 2021-02-14 08:04

    This worked for me:

    UIViewController * rootViewController = (UIViewController *)[[[UIApplication.sharedApplication.keyWindow subviews] firstObject];
    
    0 讨论(0)
提交回复
热议问题