iOS獲取最頂層ViewController

獲取頂層ViewController的代碼如下,

extension UIViewController {
    var currentViewController: UIViewController? {
        var topVC = UIApplication.shared.keyWindow?.rootViewController
        while topVC?.presentedViewController != nil {
            topVC = _getTopViewController(vc: topVC)
        }
        return topVC
    }

    fileprivate func _getTopViewController(vc: UIViewController?) -> UIViewController? {
        guard let temp = vc else { return nil }
        if temp.isKind(of: UINavigationController.self) {
            let naviVC = temp as! UINavigationController
            return _getTopViewController(vc: naviVC.topViewController)
        } else if temp.isKind(of: UITabBarController.self) {
            let tabVC = temp as! UITabBarController
            return _getTopViewController(vc: tabVC.selectedViewController)
        } else {
            return vc
        }
    }
}

The view controller that is presented by this view controller, or one of its ancestors in the view controller hierarchy.

When you present a view controller modally (either explicitly or implicitly) using the present(_:animated:completion:) method, the view controller that called the method has this property set to the view controller that it presented. If the current view controller did not present another view controller modally, the value in this property is nil.

|

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,424評論 0 10
  • 打算每天畫一幅小插畫 day1. 周末看了一下午的《地球動脈》 每一幀都可以當作絕佳繪畫素材的紀錄片 豆瓣9.7不...
    芝士魚閱讀 367評論 5 3
  • 初冬,貴人南來,周余,如飄鴻翩然北歸。 秋闌冬近氣微寒,仙女下東南。公園信步,奇峰登頂,夕照立花間。 歸云一去江城...
    晴鶴1閱讀 152評論 4 14
  • 只喜歡每天平平淡淡,不想有所成長的人,可以X掉頁面然后取消對景橋關注了,以下內容特別奉獻給每一天都希望能迎接新的自...
    Larissa閱讀 305評論 0 0
  • 北雁南飛 故鄉的土地上 已是霜白稻黍黃 曾經祖母晾曬的壩場 父親吹笛的竹院 或許早已廠房林立,車流浩蕩 還要回去嗎...
    錦茱萸閱讀 294評論 5 15