0

I have a problem with auto view poping pushed view via Navigation Link. On my ContentView is a list which can be changed after a few seconds, but if I push a new view before it, new view pops automatically after new data appears. It is unexpected behaviour. Is it a SwiftUI 3 bug or my mistake? Problem on iOS 15

My View Model

    class ViewModel: ObservableObject {
       @Published var list: [Int] = [1, 2, 3, 4, 5, 6, 7, 8]

       func changeAfterTime() {
           DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in
               self?.list = [9,10,11]
           }
       }
    }

My ContentView

    struct ContentView: View {

        @EnvironmentObject var viewModel: ViewModel
        @State private var selection: Int?

        var body: some View {
            NavigationView {
               List(viewModel.list, id: \.self) { element in
                   VStack {
                       Text(element, format: .number)
                       NavigationLink("", tag: element, selection: $selection) {
                           TestView()
                   }
                   .opacity(.zero)
               }
           }
           .onAppear {
               viewModel.changeAfterTime()
           }
       }
     }
   }

struct TestView: View {
    var body: some View {
        Text("Wait")
    }
}

I attached a video with this issue enter image description here

PiterPan
  • 1,760
  • 2
  • 22
  • 43

1 Answers1

0

The NavigationLink that is active is removed along with the element when the view is recreated because the binding changed. This causes the view to animate back to the initial list.

If you add the value 8 to the list of values you set after 2 seconds, and you select 8 initially from your list you can observe that it will not pop TestView because the element 8 and its associated part of the view (including the NavigationLink) are not removed, but it still would if you selected any of the values 1 through 7.

Charles A.
  • 10,685
  • 1
  • 42
  • 39
  • Hey @Charles A. I know this case, but it isn't mine. I am interested in if is possibility to keep existing view after the array changed after 2 sec. – PiterPan Nov 18 '21 at 08:29
  • @PiterPan Ah, that was not your question. You can probably setup a `NavigationLink` outside your list (not ones in each row) that does not get removed when your list changes and then use a button in each list element to set a state value that triggers the `NavigationLink`. – Charles A. Nov 18 '21 at 17:41