iOS开发 之 UIView的布局和重绘

本文的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

参考

更多文章, 请支持我的个人博客

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容