Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI dismissing view by setting NavigationLink tag to nil

I'm trying to implement the logic of programmatic view pop in SwiftUI

I set a tag on the items and create a corresponding variable for the selected item, but when I click the button on the DetaiView screen, nothing happens.

The problem disappears if I use VStack instead of List or use the presentationMode Environment variable to release the screen, but I'd like to use List.

Code:

struct ContentView: View {
    
    @State var data: [Int] = [1, 2, 3, 4, 5]
    @State var selectedItem: Int? = nil
    
    var body: some View {
        NavigationView {
//            NavigationLink( // This make dismiss work
//                destination: DetailView(selectedItem: $selectedItem),
//                tag: 123,
//                selection: $selectedItem,
//                label: { Text("\(123)") }
//            )
            List { // VStack here make dismiss work
                ForEach(data, id: \.self) { element in
                    NavigationLink(
                        destination: DetailView(selectedItem: $selectedItem),
                        tag: element,
                        selection: $selectedItem,
                        label: { Text("\(element)") }
                    )
                    .isDetailLink(false)
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var selectedItem: Int?
//    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    
    var body: some View {
        VStack {
            Text("DETAIL")
            Button("BUTTON") {
                selectedItem = nil // Variable set to nil but nothing happens
//                presentationMode.wrappedValue.dismiss()
            }
        }
    }
}

Am I doing something wrong or is it a SwiftUI bug?

Thank you!

like image 765
Petr Tartynskikh Avatar asked Nov 29 '20 19:11

Petr Tartynskikh


1 Answers

Update: Fixed

Tested with Xcode 13.3 / iOS 15.4

Demo with just copy-pasted code:

demo

like image 79
Asperi Avatar answered Dec 10 '22 02:12

Asperi