从应用程序委托获取当前视图控制器

时间:2014-07-18 12:31:51

标签: ios objective-c delegates appdelegate

我是ios的新手。我需要知道来自app delegate的当前视图控制器..我不知道这个,我不知道实现这个。我正在使用此代码来实现此功能,但它返回null值。 我按照这个链接 - Get current view controller from the app delegate (modal is possible) 需要帮助。

12 个答案:

答案 0 :(得分:59)

这是我用来查找用户最有可能与之交互的当前视图控制器:

UIViewController + Utils.h

#import <UIKit/UIKit.h>

@interface UIViewController (Utils)

+(UIViewController*) currentViewController;

@end

<强>的UIViewController + Utils.m

#import "UIViewController+Utils.h"

@implementation UIViewController (Utils)

+(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];

}

@end

然后,当我需要应用程序中任何位置的当前视图控制器时,只需使用:

[UIViewController currentViewController]

答案 1 :(得分:13)

这是swift中的一些类/静态函数,我保存在Utility类中,可以帮助你:

// Returns the most recently presented UIViewController (visible)
class func getCurrentViewController() -> UIViewController? {

    // If the root view is a navigation controller, we can just return the visible ViewController
    if let navigationController = getNavigationController() {

        return navigationController.visibleViewController
    }

    // Otherwise, we must get the root UIViewController and iterate through presented views
    if let rootController = UIApplication.sharedApplication().keyWindow?.rootViewController {

        var currentController: UIViewController! = rootController

        // Each ViewController keeps track of the view it has presented, so we
        // can move from the head to the tail, which will always be the current view
        while( currentController.presentedViewController != nil ) {

            currentController = currentController.presentedViewController
        }
        return currentController
    }
    return nil
}

// Returns the navigation controller if it exists
class func getNavigationController() -> UINavigationController? {

    if let navigationController = UIApplication.sharedApplication().keyWindow?.rootViewController  {

        return navigationController as? UINavigationController
    }
    return nil
}

答案 2 :(得分:5)

这有助于我找到可见的视图控制器。我搜索了现有的方法,但没有找到任何方法。所以我写了自己的自定义。

-(id)getCurrentViewController
{
    id WindowRootVC = [[[[UIApplication sharedApplication] delegate] window] rootViewController];

    id currentViewController = [self findTopViewController:WindowRootVC];

    return currentViewController;
}

-(id)findTopViewController:(id)inController
{
    /* if ur using any Customs classes, do like this.
     * Here SlideNavigationController is a subclass of UINavigationController.
     * And ensure you check the custom classes before native controllers , if u have any in your hierarchy.
    if ([inController isKindOfClass:[SlideNavigationController class]])
    {
        return [self findTopViewController:[inController visibleViewController]];
    }
    else */
    if ([inController isKindOfClass:[UITabBarController class]])
    {
        return [self findTopViewController:[inController selectedViewController]];
    }
    else if ([inController isKindOfClass:[UINavigationController class]])
    {
        return [self findTopViewController:[inController visibleViewController]];
    }
    else if ([inController isKindOfClass:[UIViewController class]])
    {
        return inController;
    }
    else
    {
        NSLog(@"Unhandled ViewController class : %@",inController);
        return nil;
    }
}

样品使用:

-(void)someMethod
{
    id currentVC = [self getCurrentViewController];
        if (currentVC)
        {
            NSLog(@"currentVC :%@",currentVC);
        }
}

答案 3 :(得分:4)

这取决于您设置UI的方式。如果以这种方式设置,您可以获取rootViewController并在层次结构中移动。

UIViewController *vc = self.window.rootViewController;

答案 4 :(得分:4)

UIViewController* actualVC = [anyViewController.navigationController.viewControllers lastObject];

答案 5 :(得分:3)

swift版本的jjv360很棒的答案, (我摆脱了一些冗余的回报,我认为Swift更具可读性)

func getCurrentViewController(_ vc: UIViewController) -> UIViewController? {
    if let pvc = vc.presentedViewController {
        return getCurrentViewController(pvc)
    }
    else if let svc = vc as? UISplitViewController, svc.viewControllers.count > 0 {
        return getCurrentViewController(svc.viewControllers.last!)
    }
    else if let nc = vc as? UINavigationController, nc.viewControllers.count > 0 {
        return getCurrentViewController(nc.topViewController!)
    }
    else if let tbc = vc as? UITabBarController {
        if let svc = tbc.selectedViewController {
            return getCurrentViewController(svc)
        }
    }
    return vc
}

来自AppDelegate,

    guard let rvc = self.window?.rootViewController else {
        return
    }
    if let vc = getCurrentViewController(rvc) {
        // do your stuff here
    }

答案 6 :(得分:3)

我得到了根控制器,然后遍历所呈现的VC:

 UIViewController *current = [UIApplication sharedApplication].keyWindow.rootViewController;

while (current.presentedViewController) {
    current = current.presentedViewController;
}
//now you can use current, for example to present an alert view controller:
[current presentViewController:alert animated:YES completion:nil];

答案 7 :(得分:1)

| * |从导航视图控制器获取可见视图控制器

application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)

| * |从可见视图控制器呈现

let NavVccVar = UIApplication.sharedApplication().keyWindow?.rootViewController as! UINavigationController
let ShnSrnVar = NavVccVar.visibleViewController

答案 8 :(得分:1)

这是我尝试过的最佳解决方案

+ (UIViewController*) topMostController
{
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

答案 9 :(得分:0)

我正在使用此代码 -

//in AppDelegate:

@interface AppDelegate()

{

    id lastViewController;

}


@implementation AppDelegate

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions

{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleCurrentViewController) name:@"CurrentViewController" object:nil];


}

-(void)handleCurrentViewController:(NSNotification *)notification
 {

    if([[notification userInfo] objectForKey:@"lastViewController"])
   {

        lastViewController = [[notification userInfo] objectForKey:@"lastViewController"];

    }
}

-(void)applicationDidEnterBackground:(UIApplication *)application
{  

    NSLog(@"last view controller is %@", [(UIViewController *)lastViewController class]);

}

@end

//在您要检测的每个ViewController中

@implementation SomeViewController

-(void) viewWillDisappear:(BOOL)animated 
{
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"CurrentViewController" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:self, @"lastViewController", nil]];

}

答案 10 :(得分:0)

我找到了这个,对我来说对于所有类型的segue和视图控制器都很有用。它很简单也很短,很不错。

  

+(UIViewController *)getTopController {       UIViewController * topViewController = [UIApplication sharedApplication] .keyWindow.rootViewController;

while (topViewController.presentedViewController) {
    topViewController = topViewController.presentedViewController;
}

return topViewController; }

答案 11 :(得分:0)

Swift 解决方案 对于 iOS 13+ 我们有 SceneDelgate 和多个窗口,因此您需要使用以下代码:

private func getCurrentViewController() -> UIViewController? {
    if let rootViewController = UIApplication.shared.windows.first?.rootViewController {
        
        if let presentedViewController = rootViewController.presentedViewController {
            return presentedViewController
        }
        
        return rootViewController
    }
    
    return nil
}