layoutIfNeeded 可能的实现机制
1 | -(void)layoutIfNeeded { |
其中 _needsLayout 由 setNeedsLayout 进行设置。
使用示例
现在自定义一个 UICustomView 继承自 UIView, 这个 UICustomView 中包含一个 contentView 属性和一个 edgeInsets 属性来控制contentView 的 frame。
这个自定义的 UICustomView 如下:
1 | #import <UIKit/UIKit.h> |
1 | #import "UICustomView.h" |
上面的 UICustomView 重写了 layoutSubViews 方法,并且实现了当 edgeInsets 的值发生改变,contentView 的 frame 随及发生改变。
当执行下面的动画:
1 | [UIView animateWithDuration:2 animations:^{ |
contentView 动态变小,如果 setEdgeInsets: 方法中不调用 layoutIfNeeded,那么 contentView 的变小不会在 animate 的 block 中,而是在 block 外,也就动态变小。如果 setEdgeInsets: 方法中 只调用 layoutIfNeeded,那么 contentView 的大小不会改变,因为此时 setNeedsLayout 并没有标记。
参考:What is the relationship between UIView’s setNeedsLayout, layoutIfNeeded and layoutSubviews?