Carl Taylor
Carl Taylor

Reputation: 101

How to programmatically navigate around a navigationController stack?

I am just wondering how I could programmatically navigate around a navigationController stack?

I am familiar with the method:

  [self.navigationController popToRootViewControllerAnimated:YES];

as well as:

  [self.navigationController popViewControllerAnimated:YES];

But could programatically go to ANY view controller in my navigation controller?

Please see my pic:

http://s18.postimage.org/iq1l4f721/test_xcodeproj_Main_Storyboard_storyboard.jpg?

I know I can segue to any view using the storyboard but am I right in thinking this would keep pushing new views onto the stack and eventually (in theory) I would run into problems?

Thanks

Carl.

Upvotes: 1

Views: 1831

Answers (4)

poncha
poncha

Reputation: 7866

  1. Have you read UINavigationController Class reference?

  2. UINavigationController has property NSArray *viewControllers, which holds current stack of view controllers (history).

  3. setViewControllers:animated: - Replaces the view controllers currently managed by the navigation controller with the specified items. (overrides history)

  4. popToViewController:animated: - Pops view controllers until the specified view controller is at the top of the navigation stack. (here you will need to pass an instance that exists in the history - see above)

  5. Get back to #1...

Upvotes: 0

janusfidel
janusfidel

Reputation: 8106

have you tried

for (UIViewController * viewController in self.navigationController.viewControllers) {
    if ([viewController isKindOfClass:[Number2Class class]]) {
        [self.navigationController popToViewController:viewController animated:YES];

    }
}

Upvotes: 1

The iOSDev
The iOSDev

Reputation: 5267

Use this code to navigate to the desired viewcontroller

NSArray *vcs = self.navigationController.viewControllers;
    for (UIViewController *cont in vcs) {
        if([cont class] == [YOUR_VIEWCONTROLLER_NAME class])
        {
            NSLog(@"Class Found");
        }

Upvotes: 0

George
George

Reputation: 4029

Yes , if you know the index of the controller in the stack or if you have a reference to it. Like this: [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:index] animated:TRUE];

Cheers!

Upvotes: 2

Related Questions