YongSir

专业程序员伪装者

AutoLayout 的时机

AutoLayout by YongSir🇨🇳🇨🇳
  • 视图布局相关
    1
    2
    3
    4
    5
    6

    // Called just before the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. The default is a nop.
    - (void)viewWillLayoutSubviews;

    // Called just after the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. The default is a nop.
    - (void)viewDidLayoutSubviews;

这两个在VC中方法,正如它的注释所述,会在VC的view的layoutSubviews被调用的之前和之后被调用,这也就是为什么,对一些添加到view的子视图布局之后,直到 viewDidLayoutSubviews才能得到正确的值!

  • PS
    1
    2
    3
    4
    5
    - (void)viewDidLoad
    |
    - (void)awakeFromNib
    |
    - (void)viewWillAppear:(BOOL)animated

可以看到viewDidLoad是最先的,它负责加载控制器,在它加载的过程中去查看view,如果从sb加载就去到awakeFromNib方法,然后再显示之类的,知道这些还不够,还需要知道:

1
2
3
4
5
111 viewDidload  -- self: <ZXMessgeCentreViewController: 0x1559a7280>, self.view: <UIView: 0x155f12cf0; frame = (0 0; 375 667); autoresize = W+H; layer = <CALayer: 0x155be07a0>>

222 awake -- self: <ZXMessgeCentreViewController: 0x1559a7280>, self.view: <UIView: 0x155f12cf0; frame = (0 0; 375 667); autoresize = W+H; layer = <CALayer: 0x155be07a0>>

333 viewWillAppear -- self: <ZXMessgeCentreViewController: 0x1559a7280>, self.view: <UIView: 0x155f12cf0; frame = (0 0; 375 667); autoresize = W+H; layer = <CALayer: 0x155be07a0>>

亲测Xcode7 beat 下从SB来的view已经布局,和viewDidLayoutSubviews中对比,这个方法进了2次,都是:
viewDidLayoutSubviews 中的view: <UIView: 0x12697d2d0; frame = (0 0; 375 667); autoresize = W+H; layer = <CALayer: 0x126bd2450>>

  • PPS

当然在实际使用时,最好能跟踪一下这几个方法,确定最好的时机