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!
Tested with Xcode 13.3 / iOS 15.4
Demo with just copy-pasted code:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With