Home > Software engineering >  SwiftUI dismissing .alert pops NavigationView
SwiftUI dismissing .alert pops NavigationView

Time:08-13

I've got the following sample code running on watchos 8 :

struct TestView: View {
  @State private var showingAlert = false
  
  var body: some View {
    NavigationView {
      NavigationLink {
        
        Button(action: {
          showingAlert = true
        }, label: {
          Text("Show dialog")
        })
        .alert("", isPresented: $showingAlert, actions: {
          Button("refresh") {
          }
        })
        
      } label: {
        Text("Show detail")
      }
    }
  }
}

It's a simple screen with a NavigationLinks that pushes into navigation a new view with a simple Button. On button press I'm displaying an alert with a simple button. When the alert is dismissed, the detail view is also dismissed and the interface returns back to it's original state.

It looks like this:

enter image description here

I am wondering what am I missing here. How can I dismiss the alert but remain on the second view that shows the "Show dialog" button.

CodePudding user response:

View separations and not needed NavigationView (watchOS only!).

So here is fixed code. Tested with Xcode 13.4 / watchOS 8.5

demo

struct TestView: View {
  var body: some View {
      NavigationLink {
        DestinationView()
      } label: {
        Text("Show detail")
      }
  }

  struct DestinationView: View {
    @State private var showingAlert = false
    var body: some View {
        Button(action: {
          showingAlert = true
        }, label: {
          Text("Show dialog")
        })
        .alert("", isPresented: $showingAlert, actions: {
          Button("refresh") {
          }
        })
    }
  }
}
  • Related