SwiftUI - Is there a popViewController equivalent in SwiftUI?

后端 未结 13 2072
说谎
说谎 2020-12-12 20:18

I was playing around with SwiftUI and want to be able to come back to the previous view when tapping a button, the same we use popViewController inside a

13条回答
  •  囚心锁ツ
    2020-12-12 20:59

    Use @Environment(\.presentationMode) var presentationMode to go back previous view. Check below code for more understanding.

    import SwiftUI
    
    struct ContentView: View {
    
    
        var body: some View {
    
            NavigationView {
                ZStack {
                    Color.gray.opacity(0.2)
    
                    NavigationLink(destination: NextView(), label: {Text("Go to Next View").font(.largeTitle)})
                }.navigationBarTitle(Text("This is Navigation"), displayMode: .large)
                    .edgesIgnoringSafeArea(.bottom)
            }
        }
    }
    
    struct NextView: View {
        @Environment(\.presentationMode) var presentationMode
        var body: some View {
            ZStack {
                Color.gray.opacity(0.2)
            }.navigationBarBackButtonHidden(true)
                .navigationBarItems(leading: Button(action: {
                    self.presentationMode.wrappedValue.dismiss()
                }, label: { Image(systemName: "arrow.left") }))
                .navigationBarTitle("", displayMode: .inline)
        }
    }
    
    
    struct NameRow: View {
        var name: String
        var body: some View {
            HStack {
                Image(systemName: "circle.fill").foregroundColor(Color.green)
                Text(name)
            }
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    

提交回复
热议问题