Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to navigate to a new view from navigationBar button click in SwiftUI

Learning to SwiftUI. Trying to navigate to a new view from navigation bar buttton clicked.
The sample code below:

var body: some View {
    NavigationView {
        List(0...< 5) { item in
            NavigationLink(destination: EventDetails()){
                EventView()
            }
        }
        .navigationBarTitle("Events")
            .navigationBarItems(trailing:
                NavigationLink(destination: CreateEvent()){
                    Text("Create Event")
                }
        )
    }
}
like image 302
Unikorn Avatar asked Jul 14 '19 02:07

Unikorn


1 Answers

Three steps got this working for me : first add an @State Bool to track the showing of the new view :

@State var showNewView = false

Add the navigationBarItem, with an action that sets the above property :

 .navigationBarItems(trailing:
        Button(action: {
            self.showNewView = true
        }) {
            Text("Go To Destination")
        }
    )

Finally add a navigation link somewhere in your view code (this relies on also having a NavigationView somewhere in the view stack)

NavigationLink(
            destination: MyDestinationView(),
            isActive: $showNewView
        ) {
            EmptyView()
        }.isDetailLink(false)
like image 55
Luke Smith Avatar answered Sep 19 '22 21:09

Luke Smith