1

In my StoryBoard, I have embedded my root view controller inside a Navigation Controller, and this view gets displayed when the app is launched. The user then goes through a series of views, which are basically view controllers presented modally.

I'm trying to implement a function to go back to the root view controller, so I called

-(IBAction)backToMenu{
    NSLog(@"Back to menu");
    [self.navigationController popToRootViewControllerAnimated:YES];
}

but nothing happens. If I do NSLog(@"%@", self.navigationController"); it prints null, so I guess that's the source of my problem. You can't call popToRootViewControllerAnimated: on a view controller that's been presented modally.

Unless you pass a reference to the root view controller. But is this the right approach? If so, how do you pass a reference to the root view controller? As all my view controllers are instances of a custom subclass of UIViewController, I tried doing inserting this in said class's code :

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    [[segue destinationViewController] navigationController] = [[segue sourceViewController] navigationController];    
}

but I get an error saying that navigationController is not assignable.

Any thoughts?

4

3 回答 3

0

在文档中dismissViewControllerAnimated:completion:,它说:

如果您连续呈现多个视图控制器,从而构建一个呈现视图控制器的堆栈,则在堆栈中较低的视图控制器上调用此方法会解除其直接子视图控制器以及堆栈上该子视图控制器上方的所有视图控制器。

这表明您应该保留对根视图控制器的引用(或以其他方式通知它)并在其上调用此方法。(如果您正在使用它,那么在已弃用的情况下也有类似的说明dismissModalViewControllerAnimated:。)

于 2012-05-24T15:32:53.170 回答
0

实现该方法的类是否-(IBAction)backToMenu继承自 UIViewController?当我正在实现 popToRootViewControllerAnimated 的类继承自其他类时,我会遇到错误。要保留对原始 navigatorController 的引用,我会:

  1. 在实现 backToMenu 的类中声明一个指向导航控制器指针的指针,例如:UINavigationController *navCon;yo 应该将其声明为属性,然后synthesizeit

  2. 因此,当您为此类实例化 ViewController 时,您可以执行以下操作:

TheClassViewController *theClassVC = [TheClassViewController alloc] initWithNib:@"TheClassViewController" bundle:nil];

theClassVC.navCon = self.navigationController;// 这里是你传递引用的地方

[self.navigationController pushViewController:theClassVC animated:YES];

于 2012-05-24T16:24:35.413 回答
0

刚刚解决了。

问题在于,在 StoryBoard 中,初始视图控制器是根视图控制器,而不是嵌入它的导航控制器!

一旦您将导航控制器设置为初始视图控制器(即拖动箭头使其指向它),它popToRootViewControllerAnimated就像一个魅力。

于 2012-05-25T11:27:08.367 回答