view初始化时的调用行为
初始化view时,如果frame为CGRectZero
,则view的layoutSubviews方法不会调用。如下代码中:customView1
的layoutSubviews
方法不会调用,但是customView2
的layoutSubviews
方法会调用。
CustomView *customView1 = [[CustomView alloc] initWithFrame:CGRectZero];
customView1.backgroundColor = [UIColor yellowColor];
[self.view addSubview:customView1];
CustomView *customView2 = [[CustomView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
customView2.backgroundColor = [UIColor yellowColor];
[self.view addSubview:customView2];
添加子view时的调用行为
当父视图的frame为CGRectZero
时,调用addSubview
添加子视图时,即使父视图的frame为CGRectZero
,其layoutSubviews
也会调用。
如果子视图的frame为CGRectZero
,则该子视图的layoutSubviews
不会调用。
但是如果子视图的frame不为CGRectZero
,则其layoutSubviews
会被调用。
调用顺序是:先调用父视图的layoutSubviews方法,然后调用子视图的layoutSubviews方法。
//
// CustomView *customView1 = [[CustomView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
CustomView *customView1 = [[CustomView alloc] initWithFrame:CGRectZero];
customView1.clipsToBounds = YES;
customView1.backgroundColor = [UIColor redColor];
[self.view addSubview:customView1];
CustomSubView *subView1 = [[CustomSubView alloc] initWithFrame:CGRectZero];
[customView1 addSubview:subView1];
// 在View层级树中,父View的layoutSubviews调用后,子类的layoutSubviews才会调用
CustomSubView *subView2 = [[CustomSubView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
subView2.backgroundColor = [UIColor yellowColor];
[customView1 addSubview:subView2];