如何以编程方式判断 ViewController 显示的 UIModalPresentationFormSheet 是否全屏打开?

How can I tell programmatically if a ViewController presented UIModalPresentationFormSheet opened on full screen or not?

在 iPhone 6+ 上模态呈现 ViewController 样式 UIModalPresentationFormSheet 根据方向打开方式不同。

在纵向模式下,它看起来像常规模式(与较小的 iPhones 相同)。 但在横向模式下,它以表格形式打开(类似于 iPad)。

我如何以编程方式判断实际使用了什么状态(在 VC 的生命周期中的任何地方)。

当控制器的尺寸 class 具有常规宽度时,控制器显示为 sheet 形式。

因此,在横向 iPhone 6+ 或任何方向的 iPad 上,水平尺寸 class 是常规的,并且表单显示小于全屏宽度。

您可以使用以下方法在控制器中对此进行测试:

if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassRegular) {
  // ... Its showing as per the form specification
}
else{
  // ... Its showing as a modal full screen.
}

如果从其他地方调用,请将 self 替换为控制器的变量。

这也涵盖了您可能使用弹出框的情况,因为当您在 iPad 上使用弹出框时,大小 class 在弹出框本身内变为紧凑。

下面是一个干净的 Swift 解决方案。添加 isBeingPresentedInFormSheet 方法的 UIViewController 扩展。

extension UIViewController {
    func isBeingPresentedInFormSheet() -> Bool {
        if let presentingViewController = presentingViewController {
            return traitCollection.horizontalSizeClass == .Compact && presentingViewController.traitCollection.horizontalSizeClass == .Regular
        }
        return false
    }
}

如果视图控制器当前显示在窗体中,则此方法returns为真 Sheet。

根据我的经验,这种情况发生在

modalPresentationStyle = .FormSheet

并且设备是 iPad 或 iPhone 6 Plus 横向。