How to get the active view in an iOS application f

2019-03-17 22:49发布

问题:

how can i get the currently active view (the main view currently being viewed by the user) from the app delegate for references sake?

回答1:

UIWindow *window = [[UIApplication sharedApplication] keyWindow];
UIView *topView = window.rootViewController.view;


回答2:

All top answers doesn't work with modal presented views! Use this code instead:

UIView * topView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];



回答3:

It depends on how your app is set up.

Typically, your app delegate will have a main view controller property that will let you get to it.

To get your app delegate

MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

UIView *topView = appDelegate.viewController.view;

If your app has a navigation controller property in the app delegate you can do something like this.

UIView *topView = appDelegate.navigationController.topViewController.view;


回答4:

I found this and it works great for me for all types of segues and view controllers.

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

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

    return topViewController;
}


回答5:

you can use [appDelegate.navigationController.topViewController class] to log the class of the controller or get the title property to know which one it is.



回答6:

Hope this helps you

UINavigationController *navCnt = (UINavigationController *)self.window.rootViewController;

if([navCnt.topViewController isMemberOfClass:[WebViewController class]])
{
    return UIInterfaceOrientationMaskAll;
}
else
return UIInterfaceOrientationMaskPortrait;


回答7:

Anywhere in the app you can get your rootViewController View also like that:

id<UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate];
UIView *rootView = appDelegate.window.rootViewController.view;


回答8:

Try Eric's answer:

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

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

    return topController;
}