2

In SwiftUI when a popover is displayed, it will display as either a popover or sheet depending on the device (iPad or iPhone) and window space available.

Is there a correct heuristic to check if the popover will be displayed as a popover or a sheet?

For example, on iPad, a popover will show as a sheet when multitasking and vertical or when horizontal at quarter-screen size.

pinglock
  • 982
  • 2
  • 12
  • 30
  • [Human Interface Guides: Popovers](https://developer.apple.com/design/human-interface-guidelines/ios/views/popovers/) – Yrb Mar 01 '22 at 19:44
  • maybe `@Environment(\.horizontalSizeClass)`? – ChrisR Mar 01 '22 at 22:36
  • @ChrisR, unfortunately this doesn't work because `horizontalSizeClass` is constant on iPad across all multitasking layouts. – pinglock Mar 02 '22 at 00:13

2 Answers2

1

Based on my testing you CAN use @Environment(\.horizontalSizeClass) to find out:

struct ContentView: View {
    
    @Environment(\.horizontalSizeClass) var sizeClass
    
    @State private var showPopover = false
    
    var body: some View {
        Button("Show PopOver") {
            showPopover = true
        }
        .popover(isPresented: $showPopover) {
            Text(sizeClass == .regular ? "regular size" : "compact size")
                .frame(width: 300, height: 300)
        }
    }
}

enter image description here

ChrisR
  • 9,523
  • 1
  • 8
  • 26
  • 1
    ChrisR, which iPad and OS build is this? I get a popover on iPad half screen. – pinglock Mar 02 '22 at 07:43
  • iPad 9th gen Simulator iOS 15.2 – when you get a popover does it a least say regular size? – ChrisR Mar 02 '22 at 07:45
  • Interesting, I'll have to check which simulator I was using again tomorrow. I was getting `.compact` and a popover at half-screen. I believe it's an iPad 9th gen as well. – pinglock Mar 02 '22 at 07:46
1

The answer here is that I needed to pass down horizontalSizeClass from the parent view that was presenting the popover. .environment(\.horizontalSizeClass, horizontalSizeClass) Without this, the child view was reading the horizontalSizeClass that was available to it (which is always compact within a popover).

pinglock
  • 982
  • 2
  • 12
  • 30