在开发中,我们可能会遇到类似这样的需求,在模态出的登录页面,再模态弹窗,直接进行弹窗是会出现警告的(无作用,)
Re:Warning: Attempt to present on
这时就需要我们拿到当前控制器的跟控制器来进行模态弹窗等操作。以下为获取当前显示的控制器的跟控制器方法
- (UIViewController*)topViewController
{
return[selftopViewControllerWithRootViewController:[UIApplicationsharedApplication].keyWindow.rootViewController];
}
- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController
{
if([rootViewControllerisKindOfClass:[UITabBarControllerclass]]) {
UITabBarController*tabBarController = (UITabBarController*)rootViewController;
return[selftopViewControllerWithRootViewController:tabBarController.selectedViewController];
}elseif([rootViewControllerisKindOfClass:[UINavigationControllerclass]]) {
UINavigationController* navigationController = (UINavigationController*)rootViewController;
return[selftopViewControllerWithRootViewController:navigationController.visibleViewController];
}elseif(rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return[selftopViewControllerWithRootViewController:presentedViewController];
}else{
returnrootViewController;
}
}
这样就可以直接调用 [self topViewController];获取顶层控制器
[[self topViewController] presentViewController:[[UIViewController alloc] init] animated:YES completion:nil]; 如此就可以模态了