layoutSubviews:
当一个视图“认为”应该重新布局自己的子控件时,它便会自动调用自己的layoutSubviews方法,在该方法中“刷新”子控件的布局;
注意:自定义view仅仅被初始化完成,未添加至父视图中时,该view的layoutSubviews方法是不会被调用的。也即以下情况不会被调用:
CustomTableHeaderView *headerView = [[CustomTableHeaderView alloc]init];
CustomTableHeaderView *headerView = [[CustomTableHeaderView alloc]initWithFrame:CGRectMake(0, 0, CHJ_ScreenWidth, 200)];
【自定义view的】layoutSubviews方法调用时机:
(1)当被添加至父视图中时会被调用:


//方式一:
CustomTableHeaderView *headerView = [[CustomTableHeaderView alloc]init];
//方式二:
CustomTableHeaderView *headerView = [[CustomTableHeaderView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];//或CGRectMakeZone
//方式三:
CustomTableHeaderView *headerView = [[CustomTableHeaderView alloc]initWithFrame:CGRectMake(0, 0, 100, 200)];
无论以何种方式创建的自定义view,当被添加至父视图中时都会触发layoutSubviews方法的调用。区别是:前两种不显示子控件,后者显示
(2)自己添加子控件时会被调用:

(3)自己的尺寸发生变化时会被调用:


注意:尺寸指的是宽或高,位置发生变化时是不会被调用的!!

另外,如果重设自己的frame时,frame还是以前的值,也是不会被调用的:
frame不发生变化时
(4)当自己的子控件尺寸发生变化时会被调用:


(5)当滚动一个UIScrollView时会触发layoutSubviews方法;
(6)当旋转屏幕时会触发layoutSubviews方法;
layoutIfNeeded:
如果需要,立即布局:
默认情况下,当有相关触发事件时,layoutSubviews方法会被调用,但这种调用机制是延迟的,而layoutIfNeeded可以保证立即调用。
那什么时候是需要呢?
有触发调用layoutSubviews方法的相关动作时,才被理解为是需要;如果不主动调用layoutIfNeeded,表明不需要,layoutSubviews方法会被延迟调用。
当layoutIfNeeded方法之前没有了相关触发操作时,layoutSubviews方法是不会被调用的,毕竟layoutIfNeeded不是layoutSubviews。
当
时间较紧,整理有点乱,望见谅。
网友评论