创建一个没有后退按钮的 NavigationLink SwiftUI

Create a NavigationLink without back button SwiftUI

我正在尝试 link SomeView1() 中的按钮操作导航到 someView2(),而无需在屏幕顶部设置后退按钮。相反,我想在 SomeView2() 中添加另一个按钮,它将导航回 SomeView1()。这在 SwiftUI 中可行吗?

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

这是它的样子:

您可以在 SomeView2() 中执行类似的操作:

NavigationView {
   VStack {
            //...view's content

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

我认为您应该在整个导航过程中只使用一个 NavigationView。现在您在彼此内部拥有三个 NavigationView,这会产生三个后退按钮。

所以在你的情况下它会变成这样:

struct SomeView1InsideNavigationView: View { // This should be the first view you present
    var body: some View {
        NavigationView { // Use NavigationView only once
            SomeView1()
        }
    }
}

struct SomeView1: View {
    var body: some View {
        VStack { // Do *not* use NavigationView here
            //...view's content

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

struct SomeView2: View {
    var body: some View {
        VStack { // Do *not* use NavigationView here
            //...view's content

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

在这里得到你想要的东西的正确方法是使用presentationMode环境变量:

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