自定义UIToolbar太靠近iPhone X上的主页指示器

我有隐藏标签栏时显示的自定义UIToolbar 。 工具栏按钮太靠近iPhone X上的主页指示灯:

 let toolbar = UIToolbar() let height = tabBarController?.tabBar.frame.height toolbar.frame = CGRect(x: 0, y: view.bounds.height - height, width: view.bounds.width, height: height) toolbar.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] view.addSubview(toolbar) 

按钮太靠近家庭指示器 按钮太靠近家庭指示器

这就是我希望它看起来像(邮件应用程序)

这就是我想要的样子(邮件应用程序)^

由于这是一个自定义视图,我知道我可以更改y位置并将其移动到安全区域的底部,但我宁愿移动按钮。 我正在使用普通的UIBarButtonItemUIBarButtonItem有灵活的空间。

iOS 11 ,Apple不赞成使用top and bottom layout guides ,而是使用单个safe area layout guide进行替换。 因此,请使用“ Safe Area Layout Guides从主页指示器移动上方视图。

使用故事板:

  • 转到StoryboardInterface Builder Document section
  • 勾选Use Safe Area Layout Guides复选框
  • 然后将Bottom Constraint更改为相对于Safe Area

现在,视图在Home Indicator上方对齐。

或者通过编码,

  toolbar.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ toolbar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), toolbar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), toolbar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), toolbar.heightAnchor.constraint(equalToConstant: 50) ]) 

有关定位相对于安全区域的内容,请参阅此文章

我也遇到了这个问题。 我的解决方案是使用通用UIView来考虑底部的safeAreaInset ,然后将工具栏添加为该视图的子视图。

 private func addToolbar(_ toolbar: UIToolbar, toView view: UIView) { toolbar.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: 0) toolbar.sizeToFit() // This sets the standard height for the toolbar. // Create a view to contain the toolbar: let toolbarParent = UIView() toolbarParent.frame = CGRect(x: 0, y: view.frame.size.height - toolbar.frame.size.height, width: toolbar.frame.size.width, height: toolbar.frame.size.height) // Adjust the position and height of the toolbar's parent view to account for safe area: if #available(iOS 11, *) { toolbarParent.frame.origin.y -= view.safeAreaInsets.bottom toolbarParent.frame.size.height += view.safeAreaInsets.bottom } toolbarParent.addSubview(toolbar) view.addSubview(toolbarParent) }