如何在 SwiftUI 中隐藏导航后退按钮?

Dan*_*Kua 32 swift swiftui

navigationBarBackButtonHidden(_ hidesBackButton: Bool) -> some View
Run Code Online (Sandbox Code Playgroud)

但它仍然显示后退按钮,我想在点击时删除后退功能。

Joa*_*nes 39

也许:

.navigationBarBackButtonHidden(true)
Run Code Online (Sandbox Code Playgroud)


小智 21

通过 navigationLink 使用

NavigationLink(destination: SomePage().navigationBarBackButtonHidden(true), tag: 1, selection: $selection) {
    //..
}
Run Code Online (Sandbox Code Playgroud)

.navigationBarBackButtonHidden(true)隐藏后退按钮。


小智 16

我尝试放置.navigationBarBackButtonHidden(true)在几个不同的地方。这是我观察到的行为。

struct PageOne: View {
    var body: some View {
        NavigationView {
            VStack{
                NavigationLink(destination: PageTwo()){
                    Text("Go to Page Two")
                }
            }
        }
    }
}

// Hide from page 2 -> page 1
struct PageTwo: View {
    var body: some View {
        VStack{
            NavigationLink(destination: PageThree()){
                Text("Go to Page Three")
            }.navigationBarBackButtonHidden(true)
        }
    }
}

// Hide from page 3 -> page 2 (Same behaviour as Kheldar's answer above)
struct PageTwo: View {
    var body: some View {
        VStack{
            NavigationLink(destination: PageThree().navigationBarBackButtonHidden(true)){
                Text("Go to Page Three")
            }
        }
    }
}


struct PageThree: View {
    var body: some View {
        Text("Hello!")
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 15

这是解决方案,但它不适用于 Xcode 11 beta 4:

struct LiveView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: ButtonView()) {
                Text("Next screen")
            }
        }
    }
}

struct ButtonView: View {
    @State var navigationBarBackButtonHidden = true

    var body: some View {
        Button("Show back") {
            self.navigationBarBackButtonHidden = false
        }.navigationBarBackButtonHidden(navigationBarBackButtonHidden)
    }
}
Run Code Online (Sandbox Code Playgroud)

还有navigationBarHidden哪些不适用于 iPhone,但它在watchOS 上完美运行。


Khe*_*dar 11

我遇到了一种情况,在我.navigationBarBackButtonHidden(true)将它放置在嵌入到NavigationLink它自身中的视图上之前,我无法使其工作。

NavigationLink(destination:MyView(stuff: aStuff, onDismiss: {})) {
         HStack {
             Text(aStuff.interestingText)
         }
} // <- used to set it here, doesn't work for me
Run Code Online (Sandbox Code Playgroud)

和:

struct MyView: View {

    var aStuff: Stuff
    var onDismiss: () -> Void

    var body: some View {
          VStack(alignment: .leading) {
               Button(action: self.onDismiss) {
                   Image(systemName: "chevron.left.circle")
               }
               CoolAnimatedStuffDisplayer(stuff: aStuff)
          }
          .navigationBarBackButtonHidden(true) // <--- works here
    }
}
Run Code Online (Sandbox Code Playgroud)