Misael Landeros
Misael Landeros

Reputation: 595

SwiftUI Rotate screen make modal don’t longer dismiss itself

I have a bug on SwiftUI, when I rotate my device the modal don't longer dismiss, the problem here is that only happen on the device on the simulator works well also on my iPad.

import SwiftUI

struct modalView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Button(action:{
            self.presentationMode.wrappedValue.dismiss()
        }){
            Text("close")
        }
    }
}

struct ContentView: View {
    @State var showModal = false
    var body: some View {
        Button(action: {
            showModal.toggle()
        }){
            Text("modal")
        }
        .sheet(isPresented: self.$showModal, content: {
            modalView()
        })
    }
}

[Bug on my device][1]

i have this problem since iOS 13 im currently on iOS 14.2 beta and Xcode 12 GM [1]: https://twitter.com/MisaelLandero/status/1306953785651142656?s=20

Upvotes: 2

Views: 765

Answers (2)

Misael Landeros
Misael Landeros

Reputation: 595

I Found the problem, I was using a condition to show two different navigations views, that break the dismiss modal

if self.sizeClass == .compact{
NavigationViewForiPhone()
} else {
NavigationViewForiPad()
} 

looks like thats the problem cuz my view is reload

Upvotes: 0

Alcides Junior
Alcides Junior

Reputation: 33

Try to use something like this:

struct ContentView: View {

  @State private var showModal = false

  // If you are getting the "can only present once" issue, add this here.
  // Fixes the problem, but not sure why; feel free to edit/explain below.
  @Environment(\.presentationMode) var presentationMode


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


struct ModalView: View {

  @Environment(\.presentationMode) private var presentationMode

  var body: some View {
    Group {
      Text("Modal view")
      Button(action: {
         self.presentationMode.wrappedValue.dismiss()
      }) {
        Text("Dismiss")
      }
    }
  }
}

Upvotes: 1

Related Questions