Replace top view in NavigationStack

165 Views Asked by At

I have a fairly complex app that uses NavigationStack with several navigationDestinations. Things were working well until I got a request to have a button which replaces the current view with a new view.

Essentially, if I have var route = NavigationPath() with a couple of items on it, I want to do this:

route.removeLast()
route.append(newDestination)

Sounds easy. When I tested this with simple views it works fine, but in the app itself, the views have many things in them (e.g., Buttons, TextFields, Pickers, etc).

Using the above route.removeLast(); route.append(newDestination) causes "nothing" to happen - the top view just remains visible. I suspect the complexity of the views is causing the problem, but I cannot simplify them.

So I introduced a delay using:

Task {
   try? await Task.sleep(for: .seconds(0.5))
   route.append(newDestination)
}

This works most of the time, but every so often it gets stuck.

I need a sure-fire way to replace the top view on a NavigationStack with another view. Any thoughts?

Each "page" or "screen" is built from a JSON description from our server. So the destination will be the same view with JSON data that provides the blueprint for views in that destination view.

1

There are 1 best solutions below

0
On

I decided to go with the delay after removing the last element before appending the new element. This works 90% or more of the time. My UI is generated from JSON and while its been optimized, it can be quite complex.

If you are running into a similar issue with NavigationStack I suggest adding this small delay to give the UI time to catch up.