nam*_*tee 8 ios swift 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)
Run Code Online (Sandbox Code Playgroud)
这就是我想要的样子(邮件应用)^
由于这是一个自定义视图,因此我知道可以更改y位置并将其移动到安全区域的底部,但是我宁愿移动按钮。我使用的是普通UIBarButtonItem格式,中间使用灵活的空格。
您不需要设置明确的高度或大小来使其工作,只需利用layoutMarginsGuide和UIBarPositioningDelegate所采用的协议即可UIToolbarDelegate。首先,布局工具栏,使其固定在视图的layoutMarginsGuide 的底部。
let constraints = [
toolbar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
toolbar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
toolbar.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor)
]
NSLayoutConstraint.activate(constraints)
Run Code Online (Sandbox Code Playgroud)
这将使工具栏与 iOS 11+ 设备上的安全区域对齐,但您需要做最后一件事才能让工具栏将其背景一直延伸到视图底部。为了使其UIToolbarDelegate在您的类中简单地符合,请将您自己设置为工具栏的委托,实现该函数position(for: UIBarPositioning) -> UIBarPosition,并返回值.bottom。UIToolbar 的 barPosition 的默认值是底部,因此在大多数用例中可能不需要最后一步。执行此操作后,您应该看到工具栏相对于安全区域布置其项目,同时将背景一直延伸到视图底部,就像您在 Mail 和 Safari 中看到的那样。
在这种情况下,使用layoutMarginsGuide而不是safeAreaLayoutGuide的优点在于,layoutMarginsGuide默认将布局边距插入安全区域。由于您不直接引用安全区域,因此您的代码可以一直向后兼容 iOS 9,而无需使用可用性检查。
在这种情况下iOS 11,Apple弃用,top and bottom layout guides而将其替换为单个safe area layout guide。因此,用于Safe Area Layout Guides将视图从主页指示器移至上方。
使用情节提要:
Storyboard和Interface Builder Document sectionUse 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)
])
Run Code Online (Sandbox Code Playgroud)
请参阅本文以相对于安全区域定位内容
| 归档时间: |
|
| 查看次数: |
3908 次 |
| 最近记录: |