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.

--

--

--

I love technology and I love a good life. What about we use technology to better everyone's lives. I'm just a drop in the ocean, but that's my goal!

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Swift iOS Background App Refresh in 3 Steps

IOS Application: How to upload IOS applications to Apple Store?

Autocomplete everything — reusing code snippets effectively

Day144 — path to iOS developer

SwiftUI | View Modifiers

Debugging Swift Compiler

Quick Guide to Swift

Swift 5

Obsolescence forced by software

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
Marlon Guerios

Marlon Guerios

I love technology and I love a good life. What about we use technology to better everyone's lives. I'm just a drop in the ocean, but that's my goal!

More from Medium

Animate a SwiftUI button

Using SwiftUI combined with Storyboard

How to adapt your View for each device

SwiftUI — Do you really understand Alignments?