详解iOS开发获取当前控制器的正取方式
背景
在开发过程中,经常需要获取当前window,rootViewController,以及当前ViewController的需求.如果.m实现不是在当前视图情况下,我们需要快速的获取到当前控制器,这种情况就需要先做好一层封装,我一般是通过UIViewController写的一个Category来实现,实现起来也非常简单,只需要我们对控制器几个方法掌握便可。
获取根控制器
+(UIViewController*)jsd_getRootViewController{
UIWindow*window=[[[UIApplicationsharedApplication]delegate]window];
NSAssert(window,@"Thewindowisempty");
returnwindow.rootViewController;
}
这里很简单,通过单例获取到当前UIApplication的delegate在通过window即可轻松拿到rootViewController。
获取当前页面控制器
+(UIViewController*)jsd_getCurrentViewController{
UIViewController*currentViewController=[selfjsd_getRootViewController];
BOOLrunLoopFind=YES;
while(runLoopFind){
if(currentViewController.presentedViewController){
currentViewController=currentViewController.presentedViewController;
}elseif([currentViewControllerisKindOfClass:[UINavigationControllerclass]]){
UINavigationController*navigationController=(UINavigationController*)currentViewController;
currentViewController=[navigationController.childViewControllerslastObject];
}elseif([currentViewControllerisKindOfClass:[UITabBarControllerclass]]){
UITabBarController*tabBarController=(UITabBarController*)currentViewController;
currentViewController=tabBarController.selectedViewController;
}else{
NSUIntegerchildViewControllerCount=currentViewController.childViewControllers.count;
if(childViewControllerCount>0){
currentViewController=currentViewController.childViewControllers.lastObject;
returncurrentViewController;
}else{
returncurrentViewController;
}
}
}
returncurrentViewController;
}
这里讲一下实现思路,我们想要与控制器无耦合的情况下,想要直接获取到当前控制器,基本都是通过rootViewController来查找的,通过上面的方法拿到rootViewControoler之后,我们先看presentedViewController,因为控制器呈现出来的方式有push与present,我们先查看它是否是present出来的,如果是则通过此属性能找到present出来的当前控制器,然后在检查是否属于UINavigationControler或UITabBarController,如果是则通过查找其子控制器里面最顶层或者其正在选择的控制器。
最后在判断当前控制器是否有子控制器的情况,如果有则取其子控制器最顶层,否则当前控制器就是其本身。
这里主要是查找当前应用程序基于UITabBarController和UINavigationControler下管理的视图控制器,如果还有其他控制器则需要添加if条件来进行判断。
presentedViewController
Apple文档presentedViewControlle
通过此方法可以查找到通过presented模态方式(显示与隐士)方式推出的当前控制器。
例如:AViewController-->BViewController通过模态方式推出.
则使用AViewController.presentedViewController能获取到BViewController。
presentingViewController
Apple文档
通过此方法可以查找到通过presented模态方式(显示与隐士)方式推出当前控制器的上层控制器。
例如:AViewController-->BViewController通过模态方式推出.
则使用BViewController.presentingViewController能获取到AViewController。
modalViewController
查看文档发现此方法已在iOS6后被弃用,官方推荐直接使用presentedViewController替代即可.
PS:通过View获取View所在的控制器
+(UIViewController*)getViewcontrollerView:(UIView*)view{
UIViewController*vc=nil;
for(UIView*temp=view;temp;temp=temp.superview){
if([temp.nextResponderisKindOfClass:[UIViewControllerclass]]){
vc=(UIViewController*)temp.nextResponder;
break;
}
}
returnvc;
}
通过递归方法遍历当前View的所有子试图
+(void)getMysubViewsWithViews:(UIView*)view{
NSArray*arrayViews=view.subviews;
for(UIView*objinarrayViews){
if([objisKindOfClass:[MyViewclass]]){
NSLog(@"找到了%@",MyView);
}
[selfgetMysubViewsWithViews:obj];
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。