详解iOS 轻松获取当前控制器的正确方式
背景
在开发过程中,经常需要获取当前window,rootViewController,以及当前正在显示的 visibleController的需求.如果.m实现不是在当前视图情况下,我们需要快速的获取到当前控制器,这种情况就需要先做好一层封装,我一般是通过UIViewController写的一个Category来实现,实现起来也非常简单,只需要我们对控制器几个方法掌握便可。
获取根控制器
+(UIViewController*)jsd_getRootViewController{
UIWindow*window=[[[UIApplicationsharedApplication]delegate]window];
NSAssert(window,@"Thewindowisempty");
returnwindow.rootViewController;
}
这里很简单,通过单例获取到当前UIApplication的delegate在通过window即可轻松拿到rootViewController。
获取当前页面控制器
+(UIViewController*)jsd_findVisibleViewController{
UIViewController*currentViewController=[selfjsd_rootViewController];
BOOLrunLoopFind=YES;
while(runLoopFind){
if(currentViewController.presentedViewController){
currentViewController=currentViewController.presentedViewController;
}else{
if([currentViewControllerisKindOfClass:[UINavigationControllerclass]]){
currentViewController=((UINavigationController*)currentViewController).visibleViewController;
}elseif([currentViewControllerisKindOfClass:[UITabBarControllerclass]]){
currentViewController=((UITabBarController*)currentViewController).selectedViewController;
}elseif([currentViewControllerisKindOfClass:[UISplitViewControllerclass]]){//当需要兼容Ipad时
currentViewController=currentViewController.presentingViewController;
}else{
if(currentViewController.presentingViewController){
currentViewController=currentViewController.presentingViewController;
}else{
returncurrentViewController;
}
}
}
}
returncurrentViewController;
}
这里讲一下实现思路,我们想要与控制器无耦合的情况下,想要直接获取到当前控制器,基本都是通过 rootViewController来查找的,通过上面的方法拿到 rootViewControoler之后,我们先看 presentedViewController,因为控制器呈现出来的方式有push与present,我们先查看它是否是present出来的,如果是则通过此属性能找到present出来的当前控制器,然后在检查是否属于 UINavigationControler或 UITabBarController,如果是则通过查找其子控制器里面最顶层或者其正在选择的控制器。最后在判断当前控制器是否有子控制器的情况,如果有则取其子控制器最顶层,否则当前控制器就是其本身。
这里主要是查找当前应用程序基于UITabBarController和UINavigationControler下管理的视图控制器,如果还有其他控制器则需要添加if条件来进行判断。
方法二:当我们有正在呈现的视图控制器子View时,可通过属性nextResponder递归查找
+(nullableUIViewController*)findBelongViewControllerForView:(UIView*)view{
UIResponder*responder=view;
while((responder=[respondernextResponder]))
if([responderisKindOfClass:[UIViewControllerclass]]){
return(UIViewController*)responder;
}
returnnil;
}
presentedViewController
Apple文档presentedViewControlle
通过此方法可以查找到通过presented模态方式(显示与隐士)方式推出的当前控制器。例如:AViewController-->BViewController通过模态方式推出.则使用AViewController.presentedViewController能获取到BViewController。
presentingViewController
Apple文档
通过此方法可以查找到通过presented模态方式(显示与隐士)方式推出当前控制器的上层控制器。例如:AViewController-->BViewController通过模态方式推出.则使用BViewController.presentingViewController能获取到AViewController。
modalViewController
查看文档发现此方法已在iOS6后被弃用,官方推荐直接使用presentedViewController替代即可.
参考资料与Dome
Dome:轻松获取当前控制器
UIViewController的presentedViewController,presentingViewController和parentViewController三个属性
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。