@qidiandasheng
2017-02-23T10:31:08.000000Z
字数 2296
阅读 5882
经验性问题
iOS中最普通的push和pop,按照栈的理解一层层进入再一层层返回是最普通和常见的。
但有时候我们会有返回到指定页面的需求,这时我们就需要用到一些特别的方法了。
首先明确一个UINavigationController的概念,我们在编程中常常会用到UINavigationController,而我们的push和pop是在UINavigationController的基础上进行的。
我们可以把UINavigationController比作是一个数组,每一个UIViewController都是数组上面的一个元素,我们不停的在数组上面add(push)和remove(pop),只是我们一直操作的是最后一个元素而已。
我们现在在最简单的一个UINavigationController上进行push和pop。如下图所示:

这里有两种方式提供返回到指定页面。我们从Controller4直接返回Controller1。self.navigationController得到的是当前Navigation1这个栈。所以我们可以使用一下方法返回到这个栈上的任意位置。
方法一
- (void)backOneAction{if ([self.navigationController.viewControllers count]>1) {UIViewController *viewController1 = self.navigationController.viewControllers[1];[self.navigationController popToViewController:viewController1 animated:YES];}}
方法二
- (void)backTwoAction{NSArray *controllersArray = [self.navigationController viewControllers];NSMutableArray *newViewController = [[NSMutableArray alloc] init];for (UIViewController *VC in controllersArray) {[newViewController addObject:VC];if ([VC isKindOfClass:[ViewController1 class]]) {break;}}[self.navigationController setViewControllers:newViewController animated:YES];}
这种情况就是数组里面的元素present出来另一个数组。也就是如下图所示从Controller2里新开出了一个栈Navigation2,Navigation2不在Navigation1的栈上。因为self.navigationController无法push到另一个UINavigationController,所以使用了present。

那这种情况要如何才能pop回Controller1呢?其实只要得到上一层的UINavigationController,然后把上面的方法稍微修改下就好了。
方法一
- (void)backOneAction{UINavigationController *navigationController = (UINavigationController *)self.presentingViewController;[self dismissViewControllerAnimated:NO completion:^{if ([navigationController.viewControllers count]>1) {UIViewController *viewController1 = navigationController.viewControllers[1];[navigationController popToViewController:viewController1 animated:YES];}}];}
方法二
- (void)backTwoAction{UINavigationController *navigationController = (UINavigationController *)self.presentingViewController;[self dismissViewControllerAnimated:NO completion:^{NSArray *controllersArray = [navigationController viewControllers];NSMutableArray *newViewController = [[NSMutableArray alloc] init];for (UIViewController *VC in controllersArray) {[newViewController addObject:VC];if ([VC isKindOfClass:[ViewController1 class]]) {break;}}[navigationController setViewControllers:newViewController animated:YES];}];}
写UINavigationController的分类,可以快速的pop回任意层。
