OC学习19:UIView的生命周期

张建 lol

UIView生命周期相关函数

    • (instancetype)initWithFrame:(CGRect)frame;

构造方法,初始化时调用,不会调用init方法

  • -(instancetype)init

构造方法,内部会调用initWithFrame方法

    • (instancetype)initWithCoder:(NSCoder *)aDecoder;

xib归档初始化视图后调用,如果xib中添加了子控件会在didAddSubview方法调用后调用

    • (void)awakeFromNib;

唤醒xib,可以布局子控件

  • -(void)willMoveToSuperview:(UIView *)newSuperview

父视图将要更改为指定的父视图,当前视图被添加到父视图时调用

  • -(void)didMoveToSuperview

父视图已更改时调用

  • -(void)willMoveToWindow:(UIWindow *)newWindow

其窗口对象将要更改时调用

  • -(void)didMoveToWindow

窗口对象已经更改时调用

  • -(void)layoutSubviews

布局子控件

  • -(void)drawRect:(CGRect)rect

绘制视图

  • -(void)dealloc

销毁

    • (void)didAddSubview:(UIView *)subview;

添加子控件时调用

    • (void)willRemoveSubview:(UIView *)subview;

将要移除子控件

init方式创建视图,并添加到父视图中展示,不添加子控件,其生命周期调用顺序为:

[NoXibView initWithFrame:]
[NoXibView init]
[NoXibView willMoveToSuperview:]
[NoXibView didMoveToSuperview]
[NoXibView willMoveToWindow:]
[NoXibView didMoveToWindow]
[NoXibView layoutSubviews]

initWithFrame方式创建视图,并添加到父视图中展示,不添加子控件,其生命周期调用顺序为:

[NoXibView initWithFrame:]
[NoXibView willMoveToSuperview:]
[NoXibView didMoveToSuperview]
[NoXibView willMoveToWindow:]
[NoXibView didMoveToWindow]
[NoXibView layoutSubviews]
[NoXibView drawRect:]

移除销毁是调用顺序:

[NoXibView willMoveToWindow:]
[NoXibView didMoveToWindow]
[NoXibView willMoveToSuperview:]
[NoXibView didMoveToSuperview]
[NoXibView removeFromSuperview]
[NoXibView dealloc]

添加子控件展示时调用顺序:

[NoXibView initWithFrame:]
[NoXibView didAddSubview:]
[NoXibView willMoveToSuperview:]
[NoXibView didMoveToSuperview]
[NoXibView willMoveToWindow:]
[NoXibView didMoveToWindow]
[NoXibView layoutSubviews]
[NoXibView drawRect:]

添加子控件移除销毁时调用顺序:

[NoXibView willMoveToWindow:]
[NoXibView didMoveToWindow]
[NoXibView willMoveToSuperview:]
[NoXibView didMoveToSuperview]
[NoXibView removeFromSuperview]
[NoXibView dealloc]
[NoXibView willRemoveSubview:]

xib创建初始化视图, xib中不添加子控件时调用顺序:

[XibView initWithCoder:]
[XibView awakeFromNib]
[XibView willMoveToSuperview:]
[XibView didMoveToSuperview]
[XibView willMoveToWindow:]
[XibView didMoveToWindow]
[XibView layoutSubviews]
[XibView layoutSubviews]
[XibView drawRect:]

xib创建初始化视图, xib中添加子控件时调用顺序:

[XibView didAddSubview:]
[XibView initWithCoder:]
[XibView awakeFromNib]
[XibView willMoveToSuperview:]
[XibView didMoveToSuperview]
[XibView willMoveToWindow:]
[XibView didMoveToWindow]
[XibView layoutSubviews]
[XibView layoutSubviews]
[XibView drawRect:]

移除销毁时调用顺序,有子控件:

[XibView willMoveToWindow:]
[XibView didMoveToWindow]
[XibView willMoveToSuperview:]
[XibView didMoveToSuperview]
[XibView removeFromSuperview]
[NoXibView dealloc]
[NoXibView willRemoveSubview:]

  • Post title:OC学习19:UIView的生命周期
  • Post author:张建
  • Create time:2023-03-10 05:03:36
  • Post link:https://redefine.ohevan.com/2023/03/10/OC/OC学习19:UIView的生命周期/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.