从iOS“安全区域”中排除导航栏

coh*_*air 5 ios autolayout ios-autolayout iphone-x

在我的 iOS 应用程序中,我在导航栏下方呈现了视图。这是因为导航栏是隐藏的,直到用户点击屏幕。

下面的屏幕截图说明了我的问题。

“X”按钮呈现在 iPhone X 的缺口下方,几乎看不到。这是我将按钮限制topAnchor为其superview!.topAnchor.

请注意,这适用于除 iPhone X 之外的所有设备。

在此处输入图片说明

此屏幕截图中的“X”按钮锚定在其上superview!.safeAreaLayoutGuide.topAnchor并呈现在导航栏下方。考虑到 Apple 的文档,这是有道理的safeAreaLayoutGuide

“本指南反映了导航栏、标签栏、工具栏和其他祖先视图未涵盖的视图部分。”

在此处输入图片说明

但是,我希望“X”按钮呈现在 iPhone X 的缺口下方和导航栏下方。这是隐藏导航栏时的样子:

在此处输入图片说明

“X”按钮应呈现在缺口正下方。

所以我的问题是:

有没有办法从视图中排除导航栏safeAreaLayoutGuide?如果没有,除了手动偏移 iPhone X 上的按钮之外,我还有什么选择。

请注意,我正在以编程方式进行所有操作。我不再使用故事板。

谢谢!

coh*_*air -1

这不是答案,而是解决方法:

  1. 保留对“X”按钮顶部约束的引用。
  2. 在 中layoutSubviews(),根据“X”的超级视图和窗口更新顶部约束的常量safeAreaInsets

override func layoutSubviews() {
    // To support devices with a "safe area". If the receiver has a top safe area, position
    // the close button beneath the _window's_ safe area.
    // Note that using the receiver's safe area does not work in this case because it includes
    // the navigation bar. We want to render the close button beneath the navigation bar.

    let windowSafeAreaInsets = UIApplication.shared.keyWindow!.safeAreaInsets

    // Only use the safe area if the receiver _and_ window have a top safe area. This handles
    // the case of non-safe area devices using a hidden navigation bar.
    closeButtonTopConstraint.constant = safeAreaInsets.top > 0 && windowSafeAreaInsets != .zero
            ? windowSafeAreaInsets.top : 16

    // Possibly do something similar for landscape and the "X" button's trailing constraint.
}
Run Code Online (Sandbox Code Playgroud)