syedfa
syedfa

Reputation: 2819

Having difficulty bypassing view controller in stack when pushing view controller in iOS

I am working on an app where I have three view controllers in sequence, ViewControllerA, ViewControllerB, and ViewControllerC. Under certain circumstances, I need the user to go from ViewControllerA directly to ViewControllerC, but unfortunately, in doing so, during the transition to ViewControllerC, ViewControllerB briefly appears on screen, which I do not want.

Here is the code that I am working with:

Inside VCA:

ViewControllerB *vcB = [ViewControllerB new];
    ViewControllerC *vcC = [ViewControllerC new];
    vcB.rootViewController = self;
    [self.navigationController pushViewController:vcB animated:NO];
    [self.navigationController pushViewController:vcC animated:YES];

As I mentioned above, the above code is happening inside ViewControllerA, and I am able to get to ViewControllerC, the problem is that unfortunately, ViewControllerB is displayed momentarily during the transition. What is it I am doing wrong, what I need to do to fix this?

Upvotes: 0

Views: 107

Answers (3)

Khanh Nguyen
Khanh Nguyen

Reputation: 11132

You can push vcC, and, once vcC is fully on the screen, quietly modify the stack to insert vcB before vcA.

ViewControllerB *vcB = [ViewControllerB new];
ViewControllerC *vcC = [ViewControllerC new];
[self.navigationController pushViewController:vcC animated:YES];

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    NSMutableArray *viewControllers = [self.navigationController.viewControllers mutableCopy];
    NSInteger indexOfC = [viewControllers indexOfObject:vcC];
    [viewControllers insertObject:vcB atIndex:indexOfC];
    [self.navigationController setViewControllers:viewControllers animated:NO];
});

Upvotes: 1

Matt S.
Matt S.

Reputation: 1892

Simple. Here's some nearly-correct-pseudocode

NSMutableArray *vcStack = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
[vcStack addObject:vcB];
[vcStack addObject:vcC];
[self.navigationController setViewControllers:vcStack animated:YES];

Obviously if you don't want the existing view stack, you can just throw it away and make your own array, however that will probably cause glitches with the animation.

Check out the docs for UINavigationController for more info: https://developer.apple.com/library/ios/documentation/Uikit/reference/UINavigationController_Class/index.html#//apple_ref/occ/instm/UINavigationController/setViewControllers:animated:

Upvotes: 3

Marcos Griselli
Marcos Griselli

Reputation: 1346

Do you need to jump directly from A to C?

then just use [self.navigationController pushViewController:vcC animated:YES];

there's no need to push B also...or you need to keep that order?

Upvotes: 0

Related Questions