【问题标题】:Calculate Height of UIView with Safe Area Guides for iPhone X使用 iPhone X 的安全区域指南计算 UIView 的高度
【发布时间】:2017-11-29 07:48:21
【问题描述】:

我有一个名为 headerview 的 UIView,我像 NavigationBar 一样使用它。它具有 60 的恒定大小和 0 的上/左/右布局约束。由于安全区域布局,除了 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;
}

【问题讨论】:

  • 不应该是'60 + topPadding'吗?
  • 是的,但是当我这样做时,因为 topPadding 是 44。结果将是 104,比实际尺寸大。

标签: ios objective-c iphone iphone-x safearealayoutguide


【解决方案1】:

试试这个。检查手机是否为 iPhoneX(如果是 iPhoneX,则顶部填充大于 0)

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

【讨论】:

  • 我做了这样的事情并且它有效,但我不知道这是否是最好的方法:)
  • 是的,我也这么想。请做一些研究
  • 注意:不能在主 ViewController 的 viewDidLoad 中调用它,因为 UIWindow 在至少一个运行循环之后才能访问。要绕过,您只需将 viewDidLoad 代码移动到新方法 postViewDidLoad 并在原始 viewDidLoad 方法中使用 [self performSelector:@selector(postViewDidLoad) afterDelay:0.0f];,然后 UIWindow 将可以访问,这将起作用。
【解决方案2】:

使用这个(swift 3):

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

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

对于 objC,使用 CGRectGetMaxY(frame)。

【讨论】:

    【解决方案3】:

    如果您使用 >= 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
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-04
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多