OC获取当前的UIViewController或者RootViewController

OC获取当前的UIViewController或者RootViewController,第1张

为UIViewController添加分类CurrentViewController 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];

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/993061.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存