肇鑫的技术博客

业精于勤,荒于嬉

Pop View and Void Stacked NavigationBars in SwiftUI

We could use SwiftUI to pop a View to another, like this

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(
                destination: PopView(),
                label: {
                    Text("Pop View")
                })
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct PopView:View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    
    var body: some View {
        Button(
            "Back",
            action: { self.presentationMode.wrappedValue.dismiss() }
        )
    }
}

This will create a button, when you press the button, a new pop up, like below.

Simulator Screen Shot - iPhone 12 Pro - 2021-08-12 at 15.49.44,

Stacked NavigationBars

import SwiftUI

struct PopSwiftUIView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    
    var body: some View {
        NavigationView {
            Button(
                "Back",
                action: { self.presentationMode.wrappedValue.dismiss() }
            ).toolbar(content: {
                Button(action: { }, label: {
                    Text("Done")
                })
            })
        }
    }
}

struct PopSwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        PopSwiftUIView()
    }
}

Simulator Screen Shot - iPhone 12 Pro - 2021-08-12 at 16.06.17

Above code will run like this, you can see the Done button is stacked to a lower level.

That is because you should only use NavigationView one time. You don't need to use it again if you previously used it.

However, in this case, you need to add NavigationView to preview yourself.

import SwiftUI

struct PopSwiftUIView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    
    var body: some View {
        Button(
            "Back",
            action: { self.presentationMode.wrappedValue.dismiss() }
        ).toolbar(content: {
            Button(action: { }, label: {
                Text("Done")
            })
        })
    }
}

struct PopSwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView {
            PopSwiftUIView()
        }
    }
}

Hide Back Button

Use .navigationBarBackButtonHidden(true) to hide the back button.

Simulator Screen Shot - iPhone 12 Pro - 2021-08-12 at 16.12.52

References