本文的Demo工程代码参考这里的StudyUIViewAndUIVC
目录
布局
layoutSubviews
- 原型
// UIView
- (void)layoutSubviews;
- 作用
Subclasses can override this method as needed to perform more precise layout of their subviews, 即对subviews重新布局
- 触发
1: 初始化时在viewDidLoad(UIViewController)之后触发
2: frame change, addSubview以及UIScrollView滚动时触发
sub view frame change以及旋转屏幕时会触发其父view的layoutSubviews
- 备注
1: 该方法不能直接调用, 必须通过setNeedsLayout或layoutIfNeeded让系统自动触发该方法
2: You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want
setNeedsLayout与layoutIfNeeded有什么区别? setNeedsLayout只是标记需要重新布局, 但不立即刷新, 配合layoutIfNeeded可以立即更新
重绘
drawRect
- 原型
// UIView
- (void)drawRect:(CGRect)rect;
- 作用
Draws the receiver’s image within the passed-in rectangle, 即重绘
- 触发
1: 初始化时在viewDidLoad(UIViewController)之后触发
2: 调用setNeedsDisplay或setNeedsDisplayInRect时触发
- 备注
1: 该方法不能直接调用, 必须通过setNeedsDisplay或setNeedsDisplayInRect让系统自动触发该方法
2: 触发drawRect有一个必要的前提: rect不能为0
参考
谈谈UIView的几个layout方法-layoutSubviews、layoutIfNeeded、setNeedsLayout...
What is the relationship between UIView's setNeedsLayout, layoutIfNeeded and layoutSubviews?
更多文章, 请支持我的个人博客