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've been creating software products for a while. Co-founded a couple of companies, and currently I'm tackling the challenges of a large airline company.

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

Recommended from Medium

Debug apps that are cold-started by a push notifications

Custom Paging UI in SwiftUI

Bring Your Mathematics Up to Speed With vDSP

Building iPhone Apps for Non-Programmers

9 little things to make your iOS application cooler

Scalable iOS Architecture Using MVVM

SwiftUI Dismiss Keyboard on outside tap

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've been creating software products for a while. Co-founded a couple of companies, and currently I'm tackling the challenges of a large airline company.

More from Medium

Animate a SwiftUI button

The missing manual to SwiftUI animations

Will be SwiftUI new future of IOS development?

Using the New iOS 15 DynamicTypeSize in SwiftUI