iOS --- 獲取屏幕頂層的UIViewController

經(jīng)常會遇到一些場景, 要通過代碼獲取到當(dāng)前顯示在屏幕最頂層的UIViewController. 如何獲取呢?

獲取rootViewController

The root view controller provides the content view of the window. Assigning a view controller to this property (either programmatically or using Interface Builder) installs the view controller’s view as the content view of the window. If the window has an existing view hierarchy, the old views are removed before the new ones are installed.

rootViewController的設(shè)定通常會在設(shè)置keyWindow的時候遇到, 表示該UIWindow的最底層的UIViewController.

UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
UIViewController *rootViewController = keyWindow.rootViewController;

獲取currentViewController

一般情況下, 可通過如下方式獲取當(dāng)前屏幕最頂層的ViewController:

- (UIViewController *)currentViewController {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
    while (vc.presentedViewController) {
        vc = vc.presentedViewController;

        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = [(UINavigationController *)vc visibleViewController];
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = [(UITabBarController *)vc selectedViewController];
        }
    }
    return vc;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 更好的閱讀體驗,請到個人博客閱讀: iOS中的系統(tǒng)轉(zhuǎn)場 請忽略標題,??,本文記錄的是對下圖所示的Kind, Pre...
    CaryaLiu閱讀 2,595評論 0 1
  • 我推薦的第一本書叫西游記,大家都知道這本書是四大名著之一,是很著名的一本書啊。我之所以推薦這本書,是有原因的,下面...
    311635a8c051閱讀 439評論 0 0
  • 慵懶的午后,一個人躺在沙發(fā)上毫無睡意,打開手機,立馬呈現(xiàn)出一條微信,送給你親愛的朋友《漂洋過海來看你》。熟悉的旋律...
    花開好時節(jié)閱讀 320評論 1 1

友情鏈接更多精彩內(nèi)容