5

Is there a way to dismiss a modal view without animation in SwiftUI?

I want to dismiss a modal without the dismiss animation because I want to navigate from the modal view to a new SwiftUI View using a view router. Everything is working, except for the transition animation from the modal view to the new full-screen view. I followed that tutorial to create a view router: Tutorial

I'm using that code snippet to present the modal view:

struct ContentView: View {

  @State private var showModal = false
  @Environment(\.presentationMode) var presentationMode


  var body: some View {
    Button(action: {
        self.showModal = true
    }) {
        Text("Show modal")
    }.sheet(isPresented: self.$showModal) {
        ModalView()
    }
  }
}


struct ModalView: View {

  @EnvironmentObject var viewRouter: ViewRouter

  var body: some View {
    Group {
      Text("Modal view")
      Button(action: {
         self.viewRouter.currentPage = "New View"
      }) {
        Text("Dismiss")
      }
    }
  }
}

Source: Answer by @M Reza Farahani

Here is a solution in Swift: Swift solution

Jonas Deichelmann
  • 3,063
  • 1
  • 28
  • 38

1 Answers1

0

Did not fully test this since I dont have the ViewRouter

You should move the

@Environment(\.presentationMode) var presentationMode

the ModalView and add

self.presentationMode.wrappedValue.dismiss()

to the button action in that ModalView

Edit:

After I added

.animation(.none)

To the ModalView it worked for me

Alright thats one ugly a** comment so putting it here:

    struct ModalView: View {

//  @EnvironmentObject var viewRouter: ViewRouter
    @Environment(\.presentationMode) var presentationMode

  var body: some View {
    Group {
      Text("Modal view")
      Button(action: {
//         self.viewRouter.currentPage = "New View"
        self.presentationMode.wrappedValue.dismiss()

      }) {
        Text("Dismiss")
      }
    }
    .animation(.none)
  }
}
Geart Otten
  • 202
  • 5
  • 8