简体   繁体   中英

How do I get the top view which is a presented view controller

I have a navigation bar controller. After some action i need to pop up a new view which is a presented view controller. Then How do i get the top view ?

I always getting top view on navigation stack but not the presented view. Why?

 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let aVariable = appDelegate.window
    if let topController = aVariable!.visibleViewController() {
        print(topController)
    }

Try

if let topController = myNavigationController.visibleViewController {
    print(topController)
}

Swift 3 example to get top UIViewController to present another UIViewController:

import UIKit

extension UIApplication {
    var topVC: UIViewController? {
        get {
            let rootVC = UIApplication.shared.keyWindow?.rootViewController

            if let nav = rootVC as? UINavigationController {
                return nav.visibleViewController
            } else if let tab = rootVC as? UITabBarController, let selected = tab.selectedViewController {
                return selected
            } else if let presented = rootVC?.presentedViewController {
                return presented
            }
            return rootVC
        }
    }
}

Can call it with:

_ = UIApplication.shared.topVC?.present(yourViewController, animated: true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM