SwiftUI - Is there a popViewController equivalent in SwiftUI?

后端 未结 13 2121
说谎
说谎 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条回答
  •  萌比男神i
    2020-12-12 21:09

    EDIT: This answer over here is better than mine, but both work: SwiftUI dismiss modal

    What you really want (or should want) is a modal presentation, which several people have mentioned here. If you go that path, you definitely will need to be able to programmatically dismiss the modal, and Erica Sadun has a great example of how to do that here: https://ericasadun.com/2019/06/16/swiftui-modal-presentation/

    Given the difference between declarative coding and imperative coding, the solution there may be non-obvious (toggling a bool to false to dismiss the modal, for example), but it makes sense if your model state is the source of truth, rather than the state of the UI itself.

    Here's my quick take on Erica's example, using a binding passed into the TestModal so that it can dismiss itself without having to be a member of the ContentView itself (as Erica's is, for simplicity).

    struct TestModal: View {
        @State var isPresented: Binding
    
        var body: some View {
            Button(action: { self.isPresented.value = false }, label: { Text("Done") })
        }
    }
    
    struct ContentView : View {
        @State var modalPresented = false
    
        var body: some View {
            NavigationView {
                Text("Hello World")
                .navigationBarTitle(Text("View"))
                .navigationBarItems(trailing:
                    Button(action: { self.modalPresented = true }) { Text("Show Modal") })
            }
            .presentation(self.modalPresented ? Modal(TestModal(isPresented: $modalPresented)) {
                self.modalPresented.toggle()
            } : nil)
        }
    }
    

提交回复
热议问题