Use NavigationLink programmatically in SwiftUI
Asked Answered
A

1

14

I'm looking for a way to display a view in my WatchOS application "one level in" from the NavigationView on app startup if certain conditions are met.

I want the same effect as if I would have pressed a NavigationLink myself, i.e being able to go back to the NavigationView again, which is not possible if I choose to display the desired view right away.

"navigationBarItems" is also not available for WatchOS which makes it impossible to navigate backwards without actually clicking the NavigationLink in the first place.

Is there a way to programmatically "click" a NavigationLink in order to achieve this?

Ankylosaur answered 11/9, 2019 at 13:10 Comment(0)
B
33

I don't have any experience with watchOS, but I've used the the "isActive" variant of NavigationLink for similar app needs.

In your initial view, define a @State var showOneLevelIn = false (or some other binding) and set that state var to true if you want the view to auto navigate to your second level. The label for the NavigationLink is an EmptyView() so it won't be visible in your initial view.

NavigationLink(destination: OneLevelInView(), isActive: $showOneLevelIn, label: { EmptyView() })

Boccie answered 11/9, 2019 at 13:37 Comment(3)
There seems to be a bug with the simulator. It only works the first time. On a real device it works without problems.Globoid
You can add .disabled(true) to turn off the navigationLink tapping, add .hidden() to disappear the navigation arrows.Duran
[iOS, not WatchOS] I found this answer when trying to hide a NavigationLink that took up space in a View. If I put my NavigationLink in a ZStack so it would not take space on the View the NavigationLink would fire when other things on top of the NavigationLink had a tapGesture. .hidden() and .disabled(true) worked perfectly in combination with the ZStack. thanks @laenhaallYul

© 2022 - 2024 — McMap. All rights reserved.