美文网首页iOS Developer
iOS获取当前屏幕控制器的方法

iOS获取当前屏幕控制器的方法

作者: 丶过客匆匆 | 来源:发表于2016-12-29 16:41 被阅读0次

1.当这个控制器是navigation控制器的子控制器时,从navigation的栈中找出你要的控制器.

//获取navigationController栈内的Viewcontroller
- (UIViewController *)getViewControlName:(NSString *)vcName
{ 
    for (id obj in self.navigationController.viewControllers)
    { 
        if ([obj isKindOfClass:NSClassFromString(vcName)]) return obj;
    } 
     return nil;
}

2.当控制器不是navigation的子控制器时.获取当前屏幕控制器的方法:
PS:获取到的是最顶层的控制器...

#pragma mark - 获取当前屏幕控制器
- (UIViewController *)getCurrentScreenViewController
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal,如果不是,找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    id  nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    //    如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder]; 
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        //        UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        
        result = nextResponder;
    }
    
    return result;
}

相关文章

网友评论

    本文标题:iOS获取当前屏幕控制器的方法

    本文链接:https://www.haomeiwen.com/subject/zykspttx.html