获取UIViewController的几个方法

UIWindow获取:

@implementation UIWindow (EZ_helper)
- (UIViewController*) ez_topMostController
{
    UIViewController *topController = [self rootViewController];
    
    //  Getting topMost ViewController
    while ([topController presentedViewController])	topController = [topController presentedViewController];
    
    //  Returning topMost ViewController
    return topController;
}

- (UIViewController*)ez_currentViewController;
{
    UIViewController *currentViewController = [self ez_topMostController];
    
    while ([currentViewController isKindOfClass:[UINavigationController class]] && [(UINavigationController*)currentViewController topViewController])
        currentViewController = [(UINavigationController*)currentViewController topViewController];
    
    return currentViewController;
}
@end

 

 

从UIView获取:

@implementation UIView (EZ_Find)
- (UIViewController *)ez_viewController
{    
    UIResponder *responder = self;
    while ((responder = [responder nextResponder])){
        if ([responder isKindOfClass: [UIViewController class]]){
            return (UIViewController *)responder;
        }
    }
    return nil;
}
@end

 

UIViewController获取:

@implementation UIViewController (EZ_Helper)


- (UIViewController*) ez_topMostController
{
    UIViewController *topController = self ;
    
    //  Getting topMost ViewController
    while ([self presentedViewController])	topController = [topController presentedViewController];
    
    //  Returning topMost ViewController
    return topController;
}

- (UIViewController*)ez_currentViewController;
{
    UIViewController *currentViewController = [self ez_topMostController];
    
    while ([currentViewController isKindOfClass:[UINavigationController class]] && [(UINavigationController*)currentViewController topViewController])
    currentViewController = [(UINavigationController*)currentViewController topViewController];
    
    return currentViewController;
}

end

 

获取当前view的UIViewController

@implementation UIViewController (EZ_Helper)

+ (UIViewController *)ez_currentViewControllerFromcurrentView{
    UIViewController *result = nil;
    // 1. get current window
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    // 2. get current View Controller
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        result = nextResponder;
    } else {
        result = window.rootViewController;
    }
    return result;
}

end

 

 

 

 

 

你可能感兴趣的:(获取UIViewController的几个方法)