layoutSubviews简要解析

官网文档介绍

The default implementation of this method does nothing on iOS 5.1 and earlier. Otherwise, the default implementation uses any constraints you have set to determine the size and position of any subviews.

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.

翻译:

这个方法的默认实现在ios5.1和更早的版本中什么都不做。否则,默认实现使用您设置的任何约束来确定任何子视图的大小和位置。

子类可以根据需要重写这个方法,以执行更精确的子视图布局。只有当子视图的自动调整大小和基于约束的行为不能提供您想要的行为时,才应该重写此方法。你可以使用你的实现直接设置子视图的框架矩形。

你不应该直接调用这个方法。如果你想强制一个布局更新,在下一次绘图更新之前调用setNeedsLayout方法。如果您想立即更新视图的布局,请调用layoutIfNeeded方法。

何时调用

stackoverflow上面的讨论结果如下:

1、init does not cause layoutSubviews to be called  

2、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
(这里描述不准确,Based on my experiment, the second rule may be not accurate: when I add `view1.2` into `view1`, `layoutSubviews` of `view1.2` and `view1` are called, but `layoutSubviews` of `view1.1` is not called. (`view1.1` and `view1.2` are subviews of `view1`). **That is, not all the subviews of the target view are called `layoutSubviews` method**.)

3、view setFrame intelligently calls layoutSubviews on the view having its frame set only if the size parameter of the frame is different

4、scrolling a UIScrollView causes layoutSubviews to be called on the scrollView, and its superview

5、rotating a device only calls layoutSubview on the parent view (the responding viewControllers primary view)

6、Resizing a view will call layoutSubviews on its superview (Important: views with an intrinsic content size will re-size if the content that determines their size changes; for example, updating the text on a UILabel will cause the intrinsic content size to be updated and thus call layoutSubviews on its superview)
复制代码

翻译:

1、init不会导致layoutsubview被调用

2、addSubview:导致layoutsubview被调用在被添加的视图,被添加的视图(目标视图),和目标的所有子视图

(根据我的实验,第二条规则可能不准确:当我添加' view1.2 '到' view1 ', ' view1.2 '和' view1 '的' layoutSubviews '被调用,但' view1.1 '的' layoutSubviews '不被调用。(“view1.1”和“view1.2”是“view1”)的子视图。也就是说,不是目标视图的所有子视图都被称为“layoutSubviews”方法**)

3、view setFrame智能地调用视图上的layoutSubviews,只有当帧的大小参数不同时才设置帧

4、滚动一个UIScrollView导致layoutSubviews被调用在scrollView和它的父视图

5、旋转设备只调用父视图上的layoutSubview(响应的viewControllers主视图)

6、调整视图的大小将在其父视图上调用layoutSubviews(重要:具有内在内容大小的视图将在内容决定其大小的变化时调整大小;例如,更新UILabel上的文本将导致内在内容大小被更新,从而调用其父视图上的layoutSubviews)
复制代码

猜你喜欢

转载自juejin.im/post/7017730151395885064