博客> iOS popToViewController到指定 VC
iOS popToViewController到指定 VC
2017-12-12 16:42 评论:0 阅读:144 Jerry_大D
ios popToViewController self.navigationController.viewControllers

废话不多说,首先明确一点 popToViewController 时都是在self.navigationController.viewControllers这个数组内进行的,如果这个数组内没有你要找的 ViewController,你直接 pop 是不可能pop 到你要得到的 vc,那么怎么解决呢?下面按步骤来说

1.0 遍历self.navigationController.viewControllers中确定是否有需要的 VC

UIViewController targetVC = nil; for (UIViewController tempVC in self.navigationController.viewControllers) { if ([tempVC isKindOfClass:[IPHomeActivityViewController class]]) { targetVC = tempVC; } }

2.0 如果有 pop 就可以了

if (targetVC) { [self.navigationController popToViewController:targetVC animated:YES]; }

3.0 重点来了,如果没有所需的 VC,那么就直接在self.navigationController.viewControllers数组后加上你要的 VC

NSMutableArray *navVCArray = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers]; [navVCArray addObject:[[IPHomeActivityViewController alloc]init]]; [self.navigationController setViewControllers:navVCArray]; NSInteger jishuwei = self.navigationController.viewControllers.count-1; [self.navigationController popToViewController:self.navigationController.viewControllers[jishuwei] animated:YES];

这样就可以了 我查阅其他大神写的 一般都是在第三步的时候不一样,他们一般是这种操作

NSMutableArray *navVCArray = [[NSMutableArray alloc] init]; [navVCArray addObject:[[IPHomeActivityViewController alloc]init]]; [self.navigationController setViewControllers:navVCArray]; NSInteger jishuwei = self.navigationController.viewControllers.count-1; [self.navigationController popToViewController:self.navigationController.viewControllers[jishuwei] animated:YES];

区别就在于navVCArray数组内的元素,如果按这种操作的话,多步 pop的时候,有可能 pop 不到以前的 VC 了,所以我的写的就是不动以前的self.navigationController.viewControllers,只增加元素即可,为了避免一直增加,增加之前就添加了第一步和第二步进行遍历查找即可。完成的代码如下:

UIViewController targetVC = nil; for (UIViewController tempVC in self.navigationController.viewControllers) { if ([tempVC isKindOfClass:[IPHomeActivityViewController class]]) { targetVC = tempVC; } } if (targetVC) { [self.navigationController popToViewController:targetVC animated:YES]; }else{ NSMutableArray *navVCArray = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers]; [navVCArray addObject:[[IPHomeActivityViewController alloc]init]]; [self.navigationController setViewControllers:navVCArray]; NSInteger jishuwei = self.navigationController.viewControllers.count-1; [self.navigationController popToViewController:self.navigationController.viewControllers[jishuwei] animated:YES]; }

欧了,不足之处还望各位批评指教

收藏
1
sina weixin mail 回到顶部