SwiftUI for iOS does not close popover

I have a default SwiftUI project for iOS. I want to have different layout for horizontal and portrait modes.

Here is my ContentView

import SwiftUI

struct ContentView: View {
    @Environment(\.verticalSizeClass) var vSizeClass
    @StateObject private var myState = MyState()
    var body: some View {
        HStack {
            if vSizeClass == .compact {
                MyView()
            } else {
                MyView()
            }
        }.environmentObject(myState)
    }
}

struct MyView: View {
    @EnvironmentObject private var myState : MyState
    var body: some View {
        Button(action: {
            myState.isShown = true
        }, label: {
            Text("Popover")
        }).popover(isPresented: $myState.isShown, content: {
            PopView()
        })
    }
}

struct PopView: View {
    @EnvironmentObject private var myState : MyState
    var body: some View {
        Button(action: {
            myState.isShown = false
        }, label: {
            Text("Close")
        })
    }
}

class MyState  : ObservableObject {
    @Published var isShown = false
}

Now I run it by selecting iPhone 13 as emulator and do the following

  • touch button Popover
  • rotate emulator view 90 degrees
  • touch button Close

Problem is the popover remains on screen and can’t be closed.

Any ideas?

Did you try it with the 'presentationMode.wrappedValue.dismiss() method? You need also the @Environment(.presentationMode) var presentationMode in your PopView.

SwiftUI for iOS does not close popover
 
 
Q