从AppDelegate获取当前视图控制器?

60
有没有一种方式从AppDelegate获取当前视图控制器?我知道有rootViewController,但这不是我想要的。
11个回答

0

如果有人想用Objective C。

GlobalManager.h

//
//  GlobalManager.h
//  Communicator
//
//  Created by Mushrankhan Pathan on 21/10/21.
//  Copyright © 2021 Ribbideo. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface GlobalManager : NSObject

typedef void (^ ActionBlock)(void);

+(UIViewController*)currentController;
+(UIViewController*)currentController:(UIViewController*) baseController;

@end

NS_ASSUME_NONNULL_END

GlobalManager.m

//
//  GlobalManager.m
//  Communicator
//
//  Created by Mushrankhan Pathan on 21/10/21.
//  Copyright © 2021 Ribbideo. All rights reserved.
//

#import "GlobalManager.h"

@implementation GlobalManager

+(UIViewController*)currentController
{
    UIViewController *base = UIApplication.sharedApplication.keyWindow.rootViewController;
    return [GlobalManager currentController:base];
}

+(UIViewController*)currentController:(UIViewController*) baseController
{
    if ([baseController isKindOfClass:[UINavigationController class]]) {
        return [GlobalManager currentController:((UINavigationController*)baseController).visibleViewController];
    }
    
    if ([baseController isKindOfClass:[UITabBarController class]]) {
        UINavigationController* moreNavigationController = ((UITabBarController*)baseController).moreNavigationController;
        UIViewController* top = moreNavigationController.topViewController;
        if (top.view.window != nil) {
            return [GlobalManager currentController:top];
        }
        UIViewController* selectedViewController = ((UITabBarController*)baseController).selectedViewController;
        if (selectedViewController != nil) {
            return [GlobalManager currentController:selectedViewController];
        }
    }
    
    if (baseController.presentedViewController != nil) {
        return [GlobalManager currentController:baseController.presentedViewController];
    }
    
    return baseController;
}

@end

如何使用。

UIViewController *currentVC = [GlobalManager currentController];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接