iOS:布局和刷新(Layout&Display)

2020-11-05  本文已影响0人  丶墨墨丶

一、layout

ios layout机制相关方法
- (CGSize)sizeThatFits:(CGSize)size
- (void)sizeToFit
- (void)layoutSubviews
- (void)layoutIfNeeded
- (void)setNeedsLayout
- (void)setNeedsDisplay
- (void)drawRect

1、 layoutSubviews

在以下情况下会被调用:

1、init初始化(内部应该是调用[self initWithFrame: CGRectZero] )不会触发layoutSubviews,但是是用initWithFrame: 进行初始化时,当rect的值不为CGRectZero时,也会触发;(前提是addSubview添加到视图上显示)

2、addSubview会触发layoutSubviews;

3、设置viewFrame会触发layoutSubviews,当然前提是frame的值设置前后发生了变化;

4、滚动一个UIScrollView会触发layoutSubviews;

5、旋转Screen会触发父UIView上的layoutSubviews事件;

6、改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件;

在苹果的官方文档中强调: You should override this method only if the autoresizing behaviors of the subviews do not offer the behavior you want.layoutSubviews, 当我们在某个类的内部调整子视图位置时,需要调用。反过来的意思就是说:如果你想要在外部设置subviews的位置,就不要重写。

刷新子对象布局-layoutSubviews方法:这个方法,默认没有做任何事情,需要子类进行重写

2、setNeedsLayout、layoutIfNeeded

3、setNeedsDisplay

layoutSubviews对subviews重新布局,layoutSubviews方法调用先于drawRectsetNeedsLayout在receiver标上一个需要被重新布局的标记,在系统runloop的下一个周期自动调用.

layoutSubviewslayoutIfNeeded方法如其名,UIKit会判断该receiver是否需要layout。

根据Apple官方文档,layoutIfNeeded方法应该是这样的,layoutIfNeeded遍历的不是superview链,应该是subviews链drawRect是对receiver的重绘,能获得context,setNeedDisplay在receiver标上一个需要被重新绘图的标记,在下一个draw周期自动重绘,iphone device的刷新频率是60hz,也就是1/60秒后重绘。

上一篇 下一篇

猜你喜欢

热点阅读