美文网首页iOS DeveloperiOS学习笔记
获取当前UIViewController,通过UIView获取所

获取当前UIViewController,通过UIView获取所

作者: Genie_GY | 来源:发表于2017-01-12 10:34 被阅读0次

    1、获取当前UIViewController

    1.1项目使用 UINavigationController --> UIViewController 结构
    + (UIViewController *)getCurViewController {
        UINavigationController *nav = (UINavigationController *)[UIApplication               sharedApplication].keyWindow.rootViewController;
        NSLog(@"当前ViewController:%@",nav.visibleViewController.class);
        return nav.visibleViewController;
    }
    
    1.2项目使用 UITabBarController --> UINavigationController --> UIViewController 结构
    + (UIViewController *)getCurViewController {
        UITabBarController *tabBarController = ((UITabBarController *)[UIApplication     sharedApplication].keyWindow.rootViewController);
        UINavigationController *nav = tabBarController.selectedViewController;
        NSLog(@"当前ViewController:%@",nav.visibleViewController.class);
        return nav.visibleViewController;
    }
    
    1.3获取present出来的ViewController
    + (UIViewController *)getPresentedViewController {
        UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
        UIViewController *presentedVC = rootVC;
        if (presentedVC.presentedViewController) {
            presentedVC = presentedVC.presentedViewController;
        }
        return presentedVC;
    }
    

    2、通过UIView获取所在的UIViewController

    - (UIViewController *)viewController {
        UIView *next = self;
        while ((next = [next superview])) {
            UIResponder *nextResponder = [next nextResponder];
            if ([nextResponder isKindOfClass:[UIViewController class]]) {
                return (UIViewController *)nextResponder;
            }
        }
        return nil;
    }
    
    在自定义UIView中实现页面跳转等操作
    [[self viewController].navigationController pushViewController:nextViewController animated:YES];
    [[self viewController].navigationController popViewControllerAnimated:YES];//返回上一个页面
    

    如有疑问或错误的地方,欢迎留言!
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    相关文章

      网友评论

        本文标题:获取当前UIViewController,通过UIView获取所

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