Swift Development — Maria Vonotna (Getty Images)

When the SwiftUI NavigationLink is too fast

Working on a new feature of my DefiniteList app, I faced a weird situation. I needed to push to a View programmatically by using NavigationLink and isActive, like so:

NavigationLink(destination: FirstView(), isActive: $showFirstView) {
EmptyView()
}
NavigationLink(destination: SecondView(), isActive: self.$navigationManager.shared.showSecondView) {
EmptyView()
}
// navigationManager is @ObservedObject

That's all fine. When I'm done with FirstView, for this feature I'm developing, I need to show push another view via NavigationLink, therefore, I set a Published variable when the FirstView is not present anymore:

struct FirstView: View {
@Environment(\.isPresented) private var isPresented
var body: some View {
VStack {
}
.onChange(of: isPresented) { isPresented in
if !isPresented {
NavigationManager.shared.showSecondView = true
}
}
}

However, the SecondView was never showing because the switch beween one view and the other was too fast. The variable NavigationManager.shared.showSecondView was set to true then to false, but nothing was being presented.

After some investigation, a simple solution made it work. You just have to slow things down a bit by using the following code when setting the isActive of the SecondView:

...
.onChange(of: isPresented) { isPresented in
if !isPresented {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
NavigationManager.shared.showSecondView = true}
}

}
}
...

And that's it. I just wanted to share this simple tip. Let me know what you guys think or if there's a better way to do it.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store