从IQKeyboard源代码分析如何获取顶层控制器

present viewcontroller
addsubview viewcontroller
tabbarcontroller viewcontrollers
uinavigationcontroller viewcontrollers

presentedViewController
被弹出的模态控制器的presentingViewController,是它的上级容器控制器。

-(UIViewController *)topMostController
{
    NSMutableArray *controllersHierarchy = [[NSMutableArray alloc] init];
    
    UIViewController *topController = self.window.rootViewController;
    
    if (topController)
    {
        [controllersHierarchy addObject:topController];
    }
    
    while ([topController presentedViewController]) {
        
        topController = [topController presentedViewController];
        [controllersHierarchy addObject:topController];
    }
    
    UIResponder *matchController = [self viewController];
    
    while (matchController != nil && [controllersHierarchy containsObject:matchController] == NO)
    {
        do
        {
            matchController = [matchController nextResponder];
            
        } while (matchController != nil && [matchController isKindOfClass:[UIViewController class]] == NO);
    }
    
    return (UIViewController*)matchController;
}


// 与下面等价?

-(UIViewController *)topMostController
{
  
    
    UIResponder *matchController = [self viewController];
    
    return ((UIViewController*)matchController).presentingViewController;
}


-(UIViewController*)viewController
{
    UIResponder *nextResponder =  self;
    
    do
    {
        nextResponder = [nextResponder nextResponder];
        
        if ([nextResponder isKindOfClass:[UIViewController class]])
            return (UIViewController*)nextResponder;
        
    } while (nextResponder != nil);
    
    return nil;
}

Paste_Image.png

nextResponder
http://www.jianshu.com/p/5c7921b7e9b6

你可能感兴趣的:(从IQKeyboard源代码分析如何获取顶层控制器)