Finding the rootViewController in iOS

后端 未结 3 1939
北荒
北荒 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 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

提交回复
热议问题