Search code examples
iosswiftswiftui

How do I return from a child view to a parent view by tapping a row element in a list in SwiftUI?


I need to perform an action similar to "unwind to segue" when the user taps and select a cell row in a list. I'm new to SwiftUI and I would really appreciate if someone can help me.


struct cellView : View {

    @State var name = ""

    var body: some View {

        VStack {
            Text(name)
            Button(action: { ***unwind to parent view code*** })
        }
    }
}

I expect there to be an action code to return to parent view after tapping the cell row.


Solution

  • You can do it using Enviroment variable called presenationMode, like this:

    struct CellView : View {
    
        @Environment(\.presentationMode) var presentationMode
        @State var name = ""
    
        var body: some View {
    
            VStack {
                Text(name)
                Button("Tap me",
                       action: { self.presentationMode.wrappedValue.dismiss() })
            }
        }
    }