iOS 根据类名,获取已存在的controller,无论是模态出来还是push出来的controller,都可以找到
我们在写代码时,有时会遇到:需要知道某个controller是否已经存在,或着,要拿到已存在的某个controller对象,这里提供一种可以获取到你想要的controller对象,只需要传入类名即可,废话不多说直接上代码:
- (UIViewController *)getActivityViewController:(NSString *)controllerName { UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController; while (topVC.presentedViewController) { topVC = topVC.presentedViewController; if ([[topVC.class description] isEqualToString:@"UINavigationController"]) { UINavigationController *navi = (UINavigationController *)topVC; if (navi && navi.viewControllers && navi.viewControllers.count > 0) { NSInteger count = navi.viewControllers.count; for (NSInteger i=count-1; i>=0; i--) { UIViewController *controller = [navi.viewControllers objectAtIndex:i]; if ([[controller.class description] isEqualToString:controllerName]) { return controller; } } } } } return nil; }
如果当前存在的同一类名的controller有多个,你要拿到最新的一个可以用下面这种方法:
- (UIViewController *)getActivityViewController:(NSString *)controllerName { UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController; UIViewController *resaultVC = nil; while (topVC.presentedViewController) { topVC = topVC.presentedViewController; if ([[topVC.class description] isEqualToString:@"UINavigationController"]) { UINavigationController *navi = (UINavigationController *)topVC; if (navi && navi.viewControllers && navi.viewControllers.count > 0) { NSInteger count = navi.viewControllers.count; for (NSInteger i=count-1; i>=0; i--) { UIViewController *controller = [navi.viewControllers objectAtIndex:i]; if ([[controller.class description] isEqualToString:controllerName]) { resaultVC = controller; } } } } } return resaultVC; }
当然这两个方法的前提是,你如果是 present 出来的congtroller,并且导航控制器是 UINavigationController 类型,如果导航控制器是自定义的,那么在判断 if ([[topVC.class description] isEqualToString:@"UINavigationController"]) 时@"UINavigationController" 要替换成你自定义的类名即可。