Created
December 7, 2016 08:26
-
-
Save cupnoodle/1af8eb772efda08012c6a3ff4abbdaaf to your computer and use it in GitHub Desktop.
Get the current active view controller on iOS screen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIViewController+Utils.m | |
// Novel | |
// | |
// Created by Axel Kee on 07/12/2016. | |
// Copyright © 2016 Javed. All rights reserved. | |
// | |
#import "UIViewController+Utils.h" | |
@interface UIViewController (Utils) | |
@end | |
@implementation UIViewController (Utils) | |
/* | |
- (void)viewDidLoad { | |
[super viewDidLoad]; | |
// Do any additional setup after loading the view. | |
} | |
- (void)didReceiveMemoryWarning { | |
[super didReceiveMemoryWarning]; | |
// Dispose of any resources that can be recreated. | |
} | |
*/ | |
+(UIViewController*) findBestViewController:(UIViewController*)vc { | |
if (vc.presentedViewController) { | |
// Return presented view controller | |
return [UIViewController findBestViewController:vc.presentedViewController]; | |
} else if ([vc isKindOfClass:[UISplitViewController class]]) { | |
// Return right hand side | |
UISplitViewController* svc = (UISplitViewController*) vc; | |
if (svc.viewControllers.count > 0) | |
return [UIViewController findBestViewController:svc.viewControllers.lastObject]; | |
else | |
return vc; | |
} else if ([vc isKindOfClass:[UINavigationController class]]) { | |
// Return top view | |
UINavigationController* svc = (UINavigationController*) vc; | |
if (svc.viewControllers.count > 0) | |
return [UIViewController findBestViewController:svc.topViewController]; | |
else | |
return vc; | |
} else if ([vc isKindOfClass:[UITabBarController class]]) { | |
// Return visible view | |
UITabBarController* svc = (UITabBarController*) vc; | |
if (svc.viewControllers.count > 0) | |
return [UIViewController findBestViewController:svc.selectedViewController]; | |
else | |
return vc; | |
} else { | |
// Unknown view controller type, return last child view controller | |
return vc; | |
} | |
} | |
+(UIViewController*) currentViewController { | |
// Find best view controller | |
UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController; | |
return [UIViewController findBestViewController:viewController]; | |
} | |
/* | |
#pragma mark - Navigation | |
// In a storyboard-based application, you will often want to do a little preparation before navigation | |
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { | |
// Get the new view controller using [segue destinationViewController]. | |
// Pass the selected object to the new view controller. | |
} | |
*/ | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment