UIView及其子类的layoutSubviews方法的调用时机

view初始化时的调用行为

初始化view时,如果frame为CGRectZero,则view的layoutSubviews方法不会调用。如下代码中:customView1layoutSubviews方法不会调用,但是customView2layoutSubviews方法会调用。

    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];

你可能感兴趣的:(UIView及其子类的layoutSubviews方法的调用时机)