iOS11 安全区域适配

来源:互联网 发布:史丹利的寓言 mac下载 编辑:程序博客网 时间:2024/05/16 11:21

1. safeAreaLayoutGuide

iOS11 中 UIView 新增加的属性,表示不被 ToolBar 、NavigationBar、iPhoneX的刘海等遮挡的区域,可以理解为 UIView 中的一个子视图,我们在写 AutoLayout 的时候就可以相对于 safeAreaLayoutGuide 来进行布局。

//在ViewController中的测试代码,bgview相对于ViewController.View.safeAreaLayoutGuide 进行布局let bgview = UIView()bgview.translatesAutoresizingMaskIntoConstraints = falsebgview.backgroundColor = UIColor.red;self.view.addSubview(bgview)let lc = NSLayoutConstraint(item: bgview, attribute: .top, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .top, multiplier: 1, constant: 0)let lc1 = NSLayoutConstraint(item: bgview, attribute: .left, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .left, multiplier: 1, constant: 0)let lc2 = NSLayoutConstraint(item: bgview, attribute: .right, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .right, multiplier: 1, constant: 0)let lc3 = NSLayoutConstraint(item: bgview, attribute: .bottom, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0)self.view.addConstraints([lc, lc1, lc2, lc3])]

这里写图片描述

2. safeAreaInsets

iOS11 中 UIView 新增加的只读属性,表示 safeAreaLayoutGuide 相对于 UIView 的边距

3. addConstraints

iOS11 中 UIViewController 新增的方法,可以用来修改安全区域的大小

//在 iPhoneX 竖屏情况下 safeAreaLayoutGuide 会布满全屏self.additionalSafeAreaInsets = UIEdgeInsetsMake(-44, 0, -34, 0)

这里写图片描述

4. viewSafeAreaInsetsDidChange

iOS11 中 UIViewController 新增的方法,当使用 additionalSafeAreaInsets 修改安全区域,或者旋转屏幕导致系统 bar 的大小发生变化时,系统会自动回调该方法。

5. safeAreaInsetsDidChange

iOS11 中 UIView 新增的方法,和 viewSafeAreaInsetsDidChange 类似