Stay weird. Stay different.

0%

AutoLayer自动布局流程

关于UIView的Layer,IOS提供了三个方法:

  • layoutSubviews:
    如果UIView的子类需要对其subviews进行精确的布局,则可以重写此方法
  • setNeedsLayout:
    此方法会将view当前的layout设置为无效的,并在下个update cycle里去触发layout更新
  • layoutIfNeeded:
    使用此方法强制立即进行layout,从当前view开始,此方法会遍历整个view层次(包括superviews)请求layout,调用此方法会强制整个view层次布局

基于约束的AutoLayer的方法:

  • setNeedsUpdateConstraints:
    当一个自定义view的某个属性发生改变,并可能影响到constraint时需要调用此方法去标记constraints需要在未来的某个点更新,系统然后调用updateConstraints
  • needsUpdateConstraints:
    constraint-based layout system使用此返回值去决定是否需要调用updateConstraints作为正常布局过程的一部分
  • updateConstraintsIfNeeded:
    立即触发约束更新,自动更新布局
  • updateConstraints:
    自定义view应该重写此方法在其中建立constraints,要在实现最后调用[super updateConstraints]

自动布局过程:

updating constraints->layout->display

  • updating constraints:
    称为测量阶段,从下向上(subview to superview)为layout做准备,可以通过调用setNeedUpdateConstraints去触发此步
  • layout:
    从上向上(superview to subview),应用上一步的信息设置viewcenterbounce。通过调用setNeedsLayout去触发这步,如果想立即更新layout可以调用layoutIfNeeded
  • display:
    此步把view渲染到屏幕上,与是否使用Auto layout无关,其操作是从下向上(superview to subview),通过调用setNeedDispaly触发

应用实例:

1
2
3
4
5
6
7
8
_viewBottomConstraint.constant = self.view.frame.size.height / 3;
//
[self.view setNeedsUpdateConstraints];

__weak RMADLoginViewController *weakSelf = self;
[UIView animateWithDuration:0.25 animations:^{
[weakSelf.view layoutIfNeeded];
}];