Last active
March 4, 2022 04:26
-
-
Save benguild/0d149bb3caaabea2dac3d2dca58c0816 to your computer and use it in GitHub Desktop.
Block for finding topmost `UIViewController` of frontmost normal-level `UIWindow`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
UIViewController *(^topmostViewControllerForFrontmostNormalLevelWindow)(void) = ^UIViewController *{ | |
// NOTE: Adapted from various stray answers here: | |
// https://stackoverflow.com/questions/6131205/iphone-how-to-find-topmost-view-controller/20515681 | |
UIViewController *viewController; | |
for (UIWindow *window in UIApplication.sharedApplication.windows.reverseObjectEnumerator.allObjects) { | |
if (window.windowLevel == UIWindowLevelNormal) { | |
viewController = window.rootViewController; | |
break; | |
} | |
} | |
while (viewController != nil) { | |
if ([viewController isKindOfClass:[UITabBarController class]]) { | |
viewController = ((UITabBarController *)viewController).selectedViewController; | |
} else if ([viewController isKindOfClass:[UINavigationController class]]) { | |
viewController = ((UINavigationController *)viewController).visibleViewController; | |
} else if (viewController.presentedViewController != nil && !viewController.presentedViewController.isBeingDismissed) { | |
viewController = viewController.presentedViewController; | |
} else if (viewController.childViewControllers.count > 0) { | |
viewController = viewController.childViewControllers.lastObject; | |
} else { | |
BOOL repeat = NO; | |
for (UIView *view in viewController.view.subviews.reverseObjectEnumerator.allObjects) { | |
if ([view.nextResponder isKindOfClass:[UIViewController class]]) { | |
viewController = (UIViewController *)view.nextResponder; | |
repeat = YES; | |
break; | |
} | |
} | |
if (!repeat) { | |
break; | |
} | |
} | |
} | |
return viewController; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment