NavigationLink Push via isActive gets dismissed immediately

Viewed 366

I want to init a navigation stack in SwiftUI. Thus I want to push a second view immediately after a first view appears. Therefore I want to use a @State var, which I set to true onAppear, and thus activates a NavigationLink.

However, the approach is not working (without modifications, see below). The push is done and then the second view is immediately dismissed (video). This is my sample (Github Repo):

struct SecondView: View {
  var body: some View {
    Text("Second")
      .navigationTitle("Second")
      .onAppear(perform: {
        print("Second: onAppear")
      })
  }
}

struct FirstView: View {
   @State var linkActive = false

   var body: some View {
     NavigationLink(destination: SecondView(), isActive: $linkActive) {
       Text("Goto second")
     }
     .navigationTitle("First")
     .onAppear(perform: {
       print("First: onAppear")
       linkActive = true
     })
     .onChange(of: linkActive) { value in
       print("First: linkActive changed to: \(linkActive)")
     }
   }
 }

 struct SwiftUIView: View {
   var body: some View {
     NavigationView {
       NavigationLink(destination: FirstView()) {
         Text("Goto first")
       }
     }
     .navigationViewStyle(StackNavigationViewStyle())
   }
}

Output:

First: onAppear
First: linkActive changed to: true
Second: onAppear
First: linkActive changed to: false

If I modify the onAppear to set the linkActive to true after a delay of min. 0.5 seconds it works. What is wrong here? I expect the SecondView to stay on screen as I don’t get why isActive is changed back to false.

0 Answers
Related