Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use NavigationLink programmatically in SwiftUI

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?

like image 363
heinz_dieter Avatar asked Sep 11 '19 13:09

heinz_dieter


People also ask

How would you create programmatic navigation in SwiftUI?

We can use SwiftUI to programmatically push a new view onto a NavigationView using NavigationLink , meaning that we can trigger the navigation when we're ready rather than just when the user tapped a button or list row.

How do I use navigation controller in SwiftUI?

Basic Navigation in SwiftUI SwiftUI has introduced the NavigationView and NavigationLink structs. These two pieces work together to allow navigation between views in your application. The NavigationView is used to wrap the content of your views, setting them up for subsequent navigation.


Video Answer


1 Answers

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() })

like image 200
KB-YYZ Avatar answered Oct 19 '22 09:10

KB-YYZ