Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI NavigationLink pop

I have navigated to a new view with NavigationLink and I want to pop back to where I was programatically. Is it yet possible in swiftUI? I know for the modal presentation we could use the .isPresented environment value but how about navigation?

like image 972
Arash Avatar asked Jul 15 '19 09:07

Arash


2 Answers

You can really simply create custom back button. Only two lines code 🔥

@Environment(\.presentationMode) var presentationMode
self.presentationMode.wrappedValue.dismiss()

Example:

import SwiftUI

struct FirstView: View {
    @State var showSecondView = false
    
    var body: some View {
        NavigationLink(destination: SecondView(),isActive : self.$showSecondView){
            Text("Push to Second View")
        }
    }
}


struct SecondView : View{
    @Environment(\.presentationMode) var presentationMode

    var body : some View {    
        Button(action:{ self.presentationMode.wrappedValue.dismiss() }){
            Text("Go Back")    
        }    
    }
}
like image 123
Sapar Friday Avatar answered Oct 18 '22 18:10

Sapar Friday


Yes you can now programmatically pop a NavigationLink View using the following code:

import SwiftUI

struct MainViewer: View {
    @State var showView = false
    var body: some View {
        
        NavigationLink(destination: DestView(showView: self.$showView),
                       isActive: self.$showView) {
          Text("Push View")                
        }
   }
}


struct DestView: View {
    @Binding var showView: Bool
    var body: some View {
    
        Button(action: {self.showView = false}) {
            Text("Pop Screen")            
        }        
    }
}
like image 14
sachin jeph Avatar answered Oct 18 '22 18:10

sachin jeph