When you present a view controller from another one, iOS will do it just fine but may complain with something along the lines of the following error message:
Warning: Attempt to present <SecondViewController: 0x7fb54b523240> on <ViewController: 0x7fb54b61e7f0> whose view is not in the window hierarchy!
This can happen when you present the second view controller with a simple method like this:
[self presentViewController:secondView animated:YES completion:nil];
What iOS has a problem with is that “self” may not be the top most view controller in the window hierarchy, from which ordinarily another view controller should be presented. Think of presenting view controllers using a navigation controller: “self” doesn’t do it; instead the navigation controller must do it, being higher up the hierarchy than the current view controller.
So rather than present from “self”, we should be presenting from the top most view controller in our keyed window, like so:
UIViewController *top = [UIApplication sharedApplication].keyWindow.rootViewController;
[top presentViewController:secondView animated:YES completion: nil];
To make sure you’re always presenting from the top most view controller, you can make use of a small helper method courtesy of akr and Darshan Kunjadiya. It goes like this:
- (UIViewController*) topMostController {
UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topController.presentedViewController) {
topController = topController.presentedViewController;
}
return topController;
}
这里附上LBXPermissionSetting里面寻找topViewController的方法
[[self currentTopViewController] presentViewController:alertController animated:YES completion:nil];
+ (UIViewController*)currentTopViewController {
UIViewController *currentViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
while ([currentViewController presentedViewController]) currentViewController = [currentViewController presentedViewController];
if ([currentViewController isKindOfClass:[UITabBarController class]]
&& ((UITabBarController*)currentViewController).selectedViewController != nil ) {
currentViewController = ((UITabBarController*)currentViewController).selectedViewController;
}
while ([currentViewController isKindOfClass:[UINavigationController class]]
&& [(UINavigationController*)currentViewController topViewController]) {
currentViewController = [(UINavigationController*)currentViewController topViewController];
}
return currentViewController;
}
网友评论