关键词
layoutSubviews, layoutIfNeeded, setNeedsLayout
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.
在iOS5.1及更早的版本中这个方法默认不执行。而在iOS5.1之后,此方法默认执行你在所有子视图中已经明确设置的所有尺寸和位置约束。
- 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.
必要时可以在子类中重写这个方法,以实现更加精细的子视图布局。只要子视图的自动尺寸调整和基于约束系统行为不能提供你想要的效果,你就应该重写这个方法,直接设置子视图的frame(来实现你想要的效果)。
- 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 thelayoutIfNeeded
method.
你不应该直接调用此方法,如果想强制更新布局,要调用setNeedsLayout
方法,但该方法不会立即 重绘视图(drawing) 。如果想立即更新 视图布局(layout) ,请调用layoutIfNeeded
方法。
什么时候系统会执行layoutSubviews
官方文档提到了layoutSubviews不是供用户来调用的,而是系统自动调用的,我们能做的就是重写该方法。那么什么时候系统会调用layoutSubviews方法呢?
- 调用
addSubview
方法时会执行该方法。 - 设置并改变子视图的frame属性时会触发该方法。
- 滑动UIScrollView及继承与UIScrollView的控件时会触发该方法。
- 旋转屏幕时,会触发父视图的layoutSubviews方法。
- 设置并改变视图的frame属性时会触发父视图的layoutSubviews方法。
layoutIfNeeded
官方描述
- Lays out the subviews immediately.
立即布局子视图。
- Use this method to force the layout of subviews before drawing. Using the view that receives the message as the root view, this method lays out the view subtree starting at the root.
使用这个方法可以在系统绘制视图之前强制(重新)布局子视图。这个方法将从当前视图开始布局当前视图树之下的所有子视图。
setNeedsLayout
官方描述
- Invalidates the current layout of the receiver and triggers a layout update during the next update cycle.
在当前布局周期发送setNeedsLayout消息是无效的,直到下一个布局周期才会触发布局更新。
- Call this method on your application’s main thread when you want to adjust the layout of a view’s subviews. This method makes a note of the request and returns immediately. Because this method does not force an immediate update, but instead waits for the next update cycle, you can use it to invalidate the layout of multiple views before any of those views are updated. This behavior allows you to consolidate all of your layout updates to one update cycle, which is usually better for performance.
当你想要调整子视图的布局时,你可以在应用的主线程调用该方法。这个方法将记录布局请求,并立即返回。由于该方法不强制立即更新,而是等到下一个更新周期,所以你可以在当前的无效周期内添加多个多个视图的布局,等到下一个周期同一更新。这么做通常可以获得更好的性能。
网友评论