50

在 iPhone X 纵向模式下,如果将安全区域的底部约束设置为 0,则屏幕底部会出现额外的空间。你如何以编程方式获得这个额外填充的高度?

我设法手动确定了这个填充的高度,它是 34,这是我设法通过 iPhone X 检测实现它的方法:

斯威夫特 4.0 和 Xcode 9.0

if UIDevice().userInterfaceIdiom == .phone
{
    switch UIScreen.main.nativeBounds.height
    {
        case 2436: //iPhone X
        self.keyboardInAppOffset.constant = -34.0
        default:
        self.keyboardInAppOffset.constant = 0
    }
}

有没有更干净的方法来检测这个填充的高度?

4

7 回答 7

72

在 iOS 11 中,视图有一个safeAreaInsets属性。如果您获得bottom这些插图的属性,您可以在 iPhone X 上获得底部填充的高度:

if #available(iOS 11.0, *) {
    let bottomPadding = view.safeAreaInsets.bottom
    // ...
}

(同样适用于带有状态栏的顶部填充)

于 2017-09-15T13:17:30.343 回答
47

Objective-C 中

if (@available(iOS 11.0, *)) {
   UIWindow *window = UIApplication.sharedApplication.keyWindow;
   CGFloat bottomPadding = window.safeAreaInsets.bottom;
}
于 2017-10-19T11:43:16.230 回答
11
var bottomPadding: CGFloat = 0.0
if #available(iOS 11.0, *) {
     let window = UIApplication.shared.keyWindow
     bottomPadding = window?.safeAreaInsets.bottom ?? 0.0
}

现在您可以bottomPadding根据需要使用。

于 2018-11-20T11:06:59.637 回答
6

如果突然没有视图,例如 CollectionViewLayout,您也可以从 Window 中检索它:

private static var itemHeight: CGFloat {
    guard #available(iOS 11.0, *),
        let window = UIApplication.shared.keyWindow else {
            return Constants.itemHeight
    }
    return Constants.itemHeight - window.safeAreaInsets.bottom
}
于 2017-10-18T14:33:33.727 回答
5

iOS 11(以上答案的混合)

let padding = UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0

于 2019-04-30T20:02:55.570 回答
5
UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0.0

iOS 13 及更高版本

于 2020-02-11T01:33:15.957 回答
2

用这条线成为你对 iPhoneX 的最低价值

if #available(iOS 11.0, *) {
            let bottomPadding = view.safeAreaInsets.bottom
  }

并且不要忘记在 layoutSubviews() 中添加它 因为 safeAreaInsets 在 layoutSubviews() 中具有正确的大小,否则您将成为错误的值。

于 2018-07-28T16:32:43.983 回答