1

I am using below code to find the top most ViewController. If alert is presented, the code above gives UIAlertController. How do I get top view controller under UIAlertController?

+(UIViewController*)topMostViewController:(UIViewController*)rootViewController
{

    if ([rootViewController isKindOfClass:[UITabBarController class]])
    {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topMostViewController:tabBarController.selectedViewController];
    }
    else if ([rootViewController isKindOfClass:[UINavigationController class]])
    {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topMostViewController:navigationController.visibleViewController];
    }
    else
    {
        return rootViewController;
    }
}

Any idea?

Steve Gear
  • 757
  • 2
  • 16
  • 44
  • How are you using the above code, and more broadly, why are you doing this check? What is it you're trying to accomplish? – Nima Yousefi Jul 04 '18 at 16:22

1 Answers1

0

Updated the answer. Since you want to find the top most view controller that is visible, you can you any of these two methods. Call this method from the view controller you are currently in by passing the UINavigation controller as parameter.

func  topMostViewController(controller:UINavigationController) -> UIViewController {

    return controller.topViewController!

}

func  visibleViewController(controller:UINavigationController) -> UIViewController {

    return controller.visibleViewController!

}
subin272
  • 733
  • 6
  • 24
  • I tried your idea to find the top most ViewController, but if alert is presented, the code above gives UIAlertController. How do I get top view controller under UIAlertController? – Steve Gear Jul 04 '18 at 10:46
  • Check the following method and see the second item in the navigation stack. self.navigationController?.viewControllers – subin272 Jul 04 '18 at 10:50
  • Thanks Subin. But this also not working. Can you please provide more info by considering my code as example – Steve Gear Jul 04 '18 at 12:34
  • Thx Subin. I want to find the top most ViewController, but if alert is presented, the code above gives UIAlertController. How do I get top view controller under UIAlertController? – Steve Gear Jul 05 '18 at 08:03
  • It worked for me. How are you presenting the alert ? Are you using UIAlertView or UIAlertController ? – subin272 Jul 05 '18 at 08:15
  • I am using UIAlertController. Can you check with my code. – Steve Gear Jul 05 '18 at 08:23
  • Did you try the code i have shared instead of your method? – subin272 Jul 05 '18 at 08:25
  • For my requirement i have to check all conditions as in my code. When alert comes then my code returns UIAlertController as topmost view controller so i want get previous top most view controller when alertController comes – Steve Gear Jul 05 '18 at 08:37