Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS – Showing a view controller already in the navigation stack

This is probably easily sorted but I can't figure it out. I have a tab bar application with two tabs, each tab has a UINavigationController.

Let's say that I in tab 1 push a viewcontroller called ItemViewController, then I go to tab 2. From tab 2 I want to programatically display the ItemViewController. So it should first take me to tab 1 and then display the ItemViewController.

This is easily achievable by just tapping on the tab 1 tab item but I want to do this programtically for other reasons.

What I'm doing right now to achieve this:

[tab1NavController popToRootViewControllerAnimated:NO];
[tabBarController setSelectedIndex:0];
[tab1NavController pushViewController:itemViewController animated:NO];

I would like to be able to do something like this in pseudo-code:

if(viewControllerIWantToDisplayIsOnNavStack)
[tab1NavController presentViewController:viewControllerIWantToDisplay];
else
//instantiate and pushviewcontroller onto stack

How can I achieve this?

like image 471
Peter Warbo Avatar asked Dec 27 '22 06:12

Peter Warbo


1 Answers

// check if the desired controller is on the stack in tab 1
if([[tab1NavController viewControllers] containsObject:viewControllerIWantToDisplay]) {
    // desired controller is on the stack, let's see if it's on top
    if(tab1NavController.topViewController == viewControllerIWantToDisplay) {
        // no need to do anything
        }
    else {
        // we need to pop to the desired view controller
        [tab1NavController popToViewController:viewControllerIWantToDisplay animated:NO];
    }
} else {
    // desired controller not on the stack
    [tab1NavController pushViewController:viewControllerIWantToDisplay animated:NO];
}

So you don't have to pop to root view controller in the tab 1 any more.

like image 154
lawicko Avatar answered Jan 11 '23 23:01

lawicko