Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a NavigationLink without back button SwiftUI

Im trying to link a button action in SomeView1() to navigate to a someView2() without having the back button at the top of the screen. Instead, I want to add another button in SomeView2() that will navigate back to SomeView1(). is this possible in SwiftUI yet?

SomeView1()

struct SomeView1: View {
    var body: some View {
        NavigationView {
            VStack {
                //...view's content

                NavigationLink(destination: SomeView2()) {
                    Text("go to SomeView2")
                }
                Spacer()
            }
        }
    }
}

SomeView2()

struct SomeView2: View {
    var body: some View {
        NavigationView {
            VStack {
                //...view's content

                NavigationLink(destination: SomeView1()) {
                    Text("go to SomeView1")
                }
                Spacer()
            }
        }
    }
}

this is what it looks like: enter image description here

like image 793
Liv Avatar asked Oct 25 '19 16:10

Liv


1 Answers

The right way to get what you want here is to use the presentationMode environment variable:

import SwiftUI

struct View2: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    var body: some View {
        VStack {
            Button(action: {
                self.presentationMode.wrappedValue.dismiss()
            }) {
                Text("POP")
            }
        }
        .navigationBarTitle("")
        .navigationBarBackButtonHidden(true)
        .navigationBarHidden(true)
    }
}

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: View2()) {
                Text("PUSH")
                    .navigationBarTitle("")
                    .navigationBarHidden(true)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
like image 166
matteopuc Avatar answered Sep 28 '22 05:09

matteopuc