iOS 获取当前页面的控制器

大家在开发的过程中,肯定会遇到一些情况,在一些工具类中需要获取当前页面的控制器。这里为大家提供一个方法方便大家使用:

OC版本:

#import "UIApplication+Extension.h"

@implementation UIApplication (Extension)

+(UIViewController *)topViewController:(UIViewController *)baseViewController {
    if (baseViewController == nil) {
        baseViewController = [[UIApplication sharedApplication] keyWindow].rootViewController;
    }
    
    if ([baseViewController isKindOfClass:[UINavigationController class]]) {
        return [UIApplication topViewController:((UINavigationController *)baseViewController).visibleViewController];
    }
    
    if ([baseViewController isKindOfClass:[UITabBarController class]]) {
        UIViewController *selectViewController = ((UITabBarController *)baseViewController).selectedViewController;
        if (selectViewController) {
            return [UIApplication topViewController:selectViewController];
        }
    }
    
    UIViewController *presentViewController = baseViewController.presentedViewController;
    if (presentViewController) {
        return [self topViewController:presentViewController];
    }
    
    return baseViewController;
}

@end

Swift版本:

import UIKit

extension UIApplication {
    
    class func topViewController(_ baseViewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationViewController = baseViewController as? UINavigationController {
            return topViewController(navigationViewController.visibleViewController)
        }
        
        if let tab = baseViewController as? UITabBarController {
            if let selected = tab.selectedViewController {
                return topViewController(selected)
            }
        }
        
        if let presented = baseViewController?.presentedViewController {
            return topViewController(presented)
        }
        
        return baseViewController
    }
    
}

你可能感兴趣的:(iOS 获取当前页面的控制器)