I have some viewControllers
, and I don't use NavigationController
. How can I get visible view controller in app delegate methods (e.g. applicationWillResignActive
)?
I know how to do it from NSNotification
, but I think it's the wrong way.
In your storyboard, select the initial view controller in your hierarchy. With this view controller selected, choose the menu item Editor -> Embed In -> Navigation Controller .
Specifying the Initial View Controllerstoryboard and select the Tab Bar Controller Scene. On the right, select the Attribute inspector. You'll find a checkbox named Is Initial View Controller. Checking this box will identify the selected view controller as the initial entry point for the storyboard you're on.
This should do it for you:
- (void)applicationWillResignActive:(UIApplication *)application { UIViewController *vc = [self visibleViewController:[UIApplication sharedApplication].keyWindow.rootViewController]; } - (UIViewController *)visibleViewController:(UIViewController *)rootViewController { if (rootViewController.presentedViewController == nil) { return rootViewController; } if ([rootViewController.presentedViewController isKindOfClass:[UINavigationController class]]) { UINavigationController *navigationController = (UINavigationController *)rootViewController.presentedViewController; UIViewController *lastViewController = [[navigationController viewControllers] lastObject]; return [self visibleViewController:lastViewController]; } if ([rootViewController.presentedViewController isKindOfClass:[UITabBarController class]]) { UITabBarController *tabBarController = (UITabBarController *)rootViewController.presentedViewController; UIViewController *selectedViewController = tabBarController.selectedViewController; return [self visibleViewController:selectedViewController]; } UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController; return [self visibleViewController:presentedViewController]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With