截图来自https://www.easck.com/videos/play/fall2017/801/
不过需要铭记的一点是这个“view”并不会显示在我们的视图层级上。
UILayoutGuides will not show up in the view hierarchy, but may be used as items in an NSLayoutConstraint and represent a rectangle in the layout engine.
在我看来,他最大的作用是作为参照物,让view可以相对某个view的safeAreaLayoutGuide做布局,从而保证view能正常、安全地显示(相对的那个view不一定要是父view)
在一种常见的使用场景里,以前我的某个view是相对于控制器的view做布局,现在是相对控制器view的safeAreaLayoutGuide做布局了
以前是这样写
[NSLayoutConstraint constraintWithItem:someView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.vc.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
现在是这样
[NSLayoutConstraint constraintWithItem:someView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.vc.view.safeAreaLayoutGuide attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
适配前后的效果

适配前.png

改成相对于view的safeAreaLayoutGuide后-竖屏.png

改成相对于view的safeAreaLayoutGuide后-横屏.png
可以看到,相同的布局下,横屏在没有statusbar时,距离顶部是0,左边是44,如果有statusbar,距离顶部就是20。反正不管怎么弄,只要我们相对safeAreaLayoutGuide做布局,我们的view就能够安全完整地显示出来
那么非iOS11怎么办?
非iOS11 还是只能对view做布局,就要写两套布局代码,稍后会介绍
这样是不是就足够应对所有情况了呢?
并不是
我们自定义的view有一边需要紧挨着屏幕边缘,比如我项目里是自定义的导航栏,它的顶部是挨着屏幕顶部的,那么导航栏就不能相对view的safeAreaLayoutGuide布局,否则顶部会空出来一截子
frame布局
这时就轮到safeAreaInsets来发挥作用啦
safeAreaInsets
先看一下safeAreaInsets的官方解释

有没有觉得和safeAreaLayoutGuide很像?safeAreaLayoutGuide可能就是根据safeAreaInsets来调整自己的bounds的










