使用 iPhone X 的安全区域指南计算 UIView 的高度

Calculate Height of UIView with Safe Area Guides for iPhone X

我有一个名为 headerview 的 UIView,我将其用作 NavigationBar。它具有 60 的恒定大小和 0 的 top/left/right 布局约束。由于安全区域布局,它对于除 iPhone X 以外的所有设备看起来都不错。如果我将大小更改为 90,它在 iPhone X 上看起来不错,但现在在其他设备上看起来不对。我用下面的代码计算安全区域的高度并将其添加到高度但现在它在其他设备中看起来很小。解决此问题的最佳方法是什么?

    if (@available(iOS 11.0, *)) {
    UIWindow *window = UIApplication.sharedApplication.keyWindow;
    CGFloat topPadding = window.safeAreaInsets.top;
    self.headerViewHeight.constant = 46 + topPadding;
}

试试这个。检查 phone 是否是 iPhone X(如果是 iPhone X,顶部填充大于 0)

if (@available(iOS 11.0, *)) {
    UIWindow *window = UIApplication.sharedApplication.keyWindow;
    CGFloat topPadding = window.safeAreaInsets.top;
    self.headerViewHeight.constant = (topPadding>0) ? 46+topPadding : 60;
 }

使用这个(swift 3):

constraint_heightTopBar.constant = UIApplication.shared.statusBarFrame.maxY + 44

所有其他设备的标准高度为 64,iPhoneX.You 的标准高度为 88,可以根据需要调整值“44”。
请记住,其他设备的状态栏高度为 20,PhoneX.So 的状态栏高度为 44,您只需根据 need.Rest 完成设置视图高度即可。
它适用于所有 iOS 版本和所有设备:-)

对于 objC,使用 CGRectGetMaxY(frame)。

如果您使用的是 >= iOS 13,那么

CGFloat safeAreaGap = 0;
UIWindow *window = UIApplication.sharedApplication.windows.firstObject;
if (window != nil) {
    safeAreaGap = window.safeAreaInsets.bottom; // for bottom
    safeAreaGap = window.safeAreaInsets.top; // for top
}

或者

if let window = UIApplication.shared.windows.first {
    self.safeAreaInsetsBottom = window.safeAreaInsets.bottom
}