Get top most UIViewController

后端 未结 24 2137
别那么骄傲
别那么骄傲 2020-11-22 14:47

I can\'t seem to get the top most UIViewController without access to a UINavigationController. Here is what I have so far:

UIApplic         


        
24条回答
  •  一整个雨季
    2020-11-22 15:31

    Based on Dianz answer, the Objective-C version

    - (UIViewController *) topViewController {
       UIViewController *baseVC = UIApplication.sharedApplication.keyWindow.rootViewController;
       if ([baseVC isKindOfClass:[UINavigationController class]]) {
           return ((UINavigationController *)baseVC).visibleViewController;
       }
    
       if ([baseVC isKindOfClass:[UITabBarController class]]) {
           UIViewController *selectedTVC = ((UITabBarController*)baseVC).selectedViewController;
           if (selectedTVC) {
               return selectedTVC;
           }
       }
    
       if (baseVC.presentedViewController) {
           return baseVC.presentedViewController;
       }
       return baseVC;
    }
    

提交回复
热议问题