堆叠多个UIViewControllers并在UINavigationController堆栈中显示最后一个

时间:2014-07-18 18:16:56

标签: objective-c ios7 uinavigationcontroller xcode5 uistoryboard

这里可能只是简单的请求,但我找不到解决方案,这让我困扰了好几天。

我正在构建简单的选项页面,用户可以跳转到所需的页面,我正在使用UINavigationController实例来管理层次结构。我的storyboard看起来像这样:

enter image description here

Viewcontrollers与下一个按钮上的push segues相关联,而我使用[self.navigationController popViewControllerAnimated:YES]作为上一个按钮。例如,如果我通过push segue在5VC和2VC上连接标记为2的按钮,我进入第二页,但如果我想使用上一个按钮,我将登陆选项页面或5VC这是我不喜欢的东西不想要。相反,我希望能够使用前一个按钮转到第一页,而在第二页。

我看到它的方式,如果我在第三页(3VC)并且我调用选项页面(5VC)并选择按钮3,系统应该堆叠1VC-2VC并呈现3VC,所以我将能够转到2VC通过[self.navigationController popViewControllerAnimated:YES]请求。

我认为解决方案与setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated有某种联系,但我不知道如何使事情有效的语法。

1 个答案:

答案 0 :(得分:0)

你有3个案例

使用push

返回中间的一个祖先

情况5VC => 2VC,5VC => 3VC:

NSArray *vcs = self.navigationController.viewControllers;
for(NSInteger i = vcs.count - 2; i > 0; i--) {

    // find the target and its parent view controller
    // i.e. class of 2VC is ViewController2
    if([vcs[i] isKindOfClass:[ViewController2 class]]) {
        UIViewController *target = vcs[i];
        UIViewController *parent = vcs[i - 1];

        // pop to its parent view controller with NO animation
        [self.navigationController popToViewController:parent animated:NO];

        // push the target from its parent
        [self.navigationController pushViewController:target animated:YES];

        return;
    }
}

使用push

返回根视图控制器

情况5VC => 1VC:

UIViewController *root = self.navigationController.viewControllers.firstObject;

// reset view controllers stack with self as root. 
[self.navigationController setViewControllers:@[self] animated:NO];

// push target from self
[self.navigationController pushViewController:root animated:YES];

// reset navigation stack with target as root.
[self.navigationController setViewControllers:@[root] animated:NO];

从一个祖先

推送新VC

情况5VC => 4VC

NSArray *vcs = self.navigationController.viewControllers;
for(NSInteger i = vcs.count - 1; i >= 0; i--) {

    // find the parent view controller
    if([vcs[i] isKindOfClass:[ViewController3 class]]) {
        UIViewController *parent = vcs[i];

        // pop to the parent with NO animation 
        [self.navigationController popToViewController:parent animated:NO];

        // perform segue from the parent
        [parent performSegueWithIdentifier:@"push4VC" sender:self];
        return;
    }
}

特别是你的情况(5VC => 4VC),你知道3VC是自己的父母,你可以直接得到父母:

NSArray *vcs = self.navigationController.viewControllers;
UIViewController *parent = vcs[vcs.count - 2]; // [vcs.count-1] is self.
[self.navigationController popToViewController:parent animated:NO];
[parent performSegueWithIdentifier:@"push4VC" sender:self];