h文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIViewController (CurrentViewController)
+ (UIViewController *)getRootViewController;
+ (UIViewController *)getCurrentViewController;
@end
NS_ASSUME_NONNULL_END```
m文件
#import "UIViewController+CurrentViewController.h"
@implementation UIViewController (CurrentViewController)
+ (UIViewController *)getRootViewController{
UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
NSAssert(window, @"The window is empty");
return window.rootViewController;
}
+ (UIViewController *)getCurrentViewController {
UIViewController* currentViewController = [self getRootViewController];
BOOL runLoopFind = YES;
while (runLoopFind) {
if (currentViewController.presentedViewController) {
currentViewController = currentViewController.presentedViewController;
} else {
if ([currentViewController isKindOfClass:[UINavigationController class]]) {
currentViewController = ((UINavigationController *)currentViewController).visibleViewController;
} else if ([currentViewController isKindOfClass:[UITabBarController class]]) {
currentViewController = ((UITabBarController* )currentViewController).selectedViewController;
} else {
break;
}
}
}
return currentViewController;
}
@end
使用
//__weak避免循环引用
__weak UIViewController *currentVC = [UIViewController getCurrentViewController];
[currentVC.navigationController pushViewController:vc animated:YES];
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)