Guillermo Suárez
Guillermo Suárez

Reputation: 158

Present deeply-nested view controller directly from anywhere whilst retaining hierarchy

I'm working on a big project and the stack is as follows.

I have a UITabBarController and for each tab a UINavigationController, containing one or more UIViewControllers.

UITabBarController > UINavigationController > UIViewController1 > UIViewController2 > ...

The normal flow would be the user tapping through each view controller. But how can I open the app for example directly to UIViewController2, whilst retaining the hierarchy?

I explicitely don't want to present a modal view from AppDelegate or push the view controller somewhere else. The desired behaviour would be similar to chat apps, that open a specific chat UIViewController2 (from a push notification, for example), but still can go "back" to the chat list view (UIViewController1 in this example), even if the app was launched directly into UIViewController2 and UIViewController1 was never presented.

Another use-case would be to do the same but from another tab instead of AppDelegate. From somewhere in tab 2, open UIViewController2 inside of tab 1.

How could this be achieved? I thought of different options, but wouldn't know how to implement them

Upvotes: 0

Views: 296

Answers (1)

ystack
ystack

Reputation: 1805

But how can I open the app for example directly to UIViewController2, whilst retaining the hierarchy?

By programmatically modifying the UINavigationController's viewControllers array hierarchy.
Suppose, you are currently on UIViewController2, some sample code to build the backstack hierarchy can be like:

NSMutableArray *controllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
UIViewController1 *VC1 = [UIViewController1 new]; 
[controllers insertObject:VC1 atIndex:(controllers.count - 1)]; // choose the index
self.navigationController.viewControllers = controllers;

A good place to perform this would be the viewDidLoad of the currently presented view controller.

Upvotes: 2

Related Questions