Gusfat Gusfat - 19 days ago 8
iOS Question

Cycle between views with navigation controller

So i want to cycle though different views controllers with a navigation controller but at the same time i want to be able to cycle back to any of the views without having to push a new instance.

The Red view is always the initial one, the user will go there after clicking in a button that is in another part of the project.

For example:

B = Blue. Red = Red G = Green.

R > Y > B.

If i go back to the Red view i dont want to create a new instance of the view, i want to retrieve the view that is in the navigation stack.

I can already retrieve what views are in the Navigation Controller with

if let viewControllers = navigationController?.viewControllers {
for viewController in viewControllers {
if viewController is RedViewController {

print("Already initialized")

}
}
}


For now im doing

self.navigationController?.pushViewController(controller, animated: false)


but its always creating a new instance of that view.

My question is: it is possible to show a specific view that is already initialized and inside a navigation view controller?

I couldn't take a good picture but imagine that the red view is embedded in a navigation controller.

enter image description here

Answer

You can use setViewControllers() to change the state of the stack from one set of view controllers to another i.e.

let viewController = navigationController?.viewControllers
// remove unneeded view controllers from the stack
_ = navigationController?.setViewControllers(viewControllers, animated: true)

In your example when you get the stack array it will contain R, Y and B, you can therefore remove Y and B to display the original R view controller.


Another way to keep view controllers permanently loaded is to create a parent view controller that contains 3 container views layered one on top of the other. (maybe you need to read up and experiment with container views, it is a view that has a view controller embedded within it).Each of the container views has one of your R, Y or B view controllers embedded within it. You switch between the 3 view controllers by changing the alpha of the container views.

i.e. to display the R view controller, the R container's view's alpha is set to 1.0 with the Y and B's container views' alpha is set to 0.0

Comments