didMoveToSuperView 引发的思考

时间:2023-03-08 21:55:55

1.

- (void)didMoveToSuperview 通知视图已经移动到一个新的父视图中

2.

/**系统自动调用(留给子类去实现)**/

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

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

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

- (void)didMoveToSuperview;                            <<< ----------------

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

- (void)didMoveToWindow;

/**系统自动调用**/

3.

iOS  UIView 类目 UIViewHierarchy

有一个方法

didMoveToSuperview

官方解释如下

Tells the view that its superview changed.

大致意思: 当view的父级视图更改的时候会调用此方法

The default implementation of this method does nothing. Subclasses can override it to perform additional actions whenever the superview changes.

大致意思:此方法默认实现,不做任何操作。子视图可以实现此方法,添加自己所需要的功能

通过以上我们可以理解为 次方法在view被添加新的父级视图的时候会调用。

我们尝试测试一下

首先新建一个项目TestDidMoveToSuperview

新建一个View 继承UIView 起名:MyTestView

didMoveToSuperView 引发的思考

  1. </pre><p></p></blockquote><p></p><p class="p1">实现方法</p><p class="p1"></p><pre name="code" class="objc">-(void)didMoveToSuperview{
  2. NSLog(@"test didMoveToSuperview");
  3. }

接下来我们在ViewController.m中添加view

  1. #import "ViewController.h"
  2. #import "MyTestView.h"
  3. @interface ViewController ()
  4. @end
  5. @implementation ViewController
  6. - (void)viewDidLoad {
  7. [super viewDidLoad];
  8. // Do any additional setup after loading the view, typically from a nib.
  9. MyTestView *testView=[[MyTestView alloc]initWithFrame:CGRectMake(10, 120, 300, 300)];
  10. testView.backgroundColor=[UIColor grayColor];
  11. [self.view addSubview:testView];
  12. }
  13. - (void)didReceiveMemoryWarning {
  14. [super didReceiveMemoryWarning];
  15. // Dispose of any resources that can be recreated.
  16. }
  17. @end

运行 是不是看到 log了

didMoveToSuperView 引发的思考

相关文章