iOS获取当前控制器的顶层控制器

编程语言 01/17 阅读 487 views次 人气 0
摘要:

在开发中,我们可能会遇到类似这样的需求,在模态出的登录页面,再模态弹窗,直接进行弹窗是会出现警告的(无作用,)

--------------------------------------------------------------------------------------------------------------------------------------

Re:Warning: Attempt to present <UINavigationController: 0x6e8ade0> on <LoginViewControl ..   -类似这样

这时就需要我们拿到当前控制器的跟控制器来进行模态弹窗等操作。以下为获取当前显示的控制器的跟控制器方法

- (UIViewController*)topViewController

{

    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];

}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController

{

    if ([rootViewController isKindOfClass:[UITabBarController class]]) {

        UITabBarController *tabBarController = (UITabBarController *)rootViewController;

        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];

    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {

        UINavigationController* navigationController = (UINavigationController*)rootViewController;

        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];

    } else if (rootViewController.presentedViewController) {

        UIViewController* presentedViewController = rootViewController.presentedViewController;

        return [self topViewControllerWithRootViewController:presentedViewController];

    } else {

        return rootViewController;

    }

}

这样就可以直接调用  [self topViewController];获取顶层控制器 

[[self topViewController] presentViewController:[[UIViewController alloc] init] animated:YES completion:nil]; 如此就可以模态了

小奋斗文章

--------------------------------------------------------------------------------------------------------------------------------------

评论

该文章不支持评论!

分享到: