- 官方文档说明
- 调用时机
- 重写场景
官方文档说明
Subclasses can override this method as needed to perform more precise layout of their subviews. You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want. You can use your implementation to set the frame rectangles of your subviews directly.
You should not call this method directly. If you want to force a layout update, call the setNeedsLayout method instead to do so prior to the next drawing update. If you want to update the layout of your views immediately, call the layoutIfNeeded method.
从官方文档我们可以知悉,layoutSubViews主要使用场景是当系统实现的布局无法满足你的要求,通过重写该方法对子控件重新布局,从而实现更精确的布局。同时该方法无法手动直接调用,可以通过调用setNeedsLayout,该方法会在界面的下一个刷新周期的时候再调用layoutSubviews方法,刷新子控件。
调用时机:
一个国外网友总结的系统调用layoutSubViews时机,列举了以下情况:
- init does not cause layoutSubviews to be called (duh)
- addSubview causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target
- view setFrame intelligently calls layoutSubviews on the view having its frame set only if the size parameter of the frame is different
- scrolling a UIScrollView causes layoutSubviews to be called on the scrollView, and its superview
- rotating a device only calls layoutSubview on the parent view (the responding viewControllers primary view)
- Resizing a view will call layoutSubviews on its superview
也就是说,layoutSubviews 方法会在这些情况下,在这些 UIView 实例上被调用:
- addSubview被调用时:父视图,以及父视图的所有子视图
- 改变一个UIView的大小:被更改size的view(更改view的位置不会触发)
- UISCrollView:滚动scrollView的时候
- 旋转设备:当前屏幕响应的viewcontro的rootView
UIView的初始化init(intiWithFrame:)并不会调用layoutSubView,同时只有UIView被添加到UIWindow的树级结构中,才有可能触发layoutSubViews
— (void)viewDidLoad {
[super viewDidLoad];
View1 *view1 = [[View1 alloc] init];
// [self.view addSubview:view1];
[view1 setFrame:CGRectMake(30, 30, 10, 10)];
}
上面的view1 改变size的时候并不会调用layoutSubView,因为view1没有添加到当前控制器的rootView中。
使用场景
You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want.
按照官方文档的说明当通过自动布局的方式无法获取想要的布局的时候,可以通过重写改方法定制更精确的布局。特别是在父视图的size频繁变动,子视图需要跟随变动布局的时候。
网友评论