The role of layoutSubview
LayoutSubview literally means layout child controls. The first thing to make clear is that the system View does not implement any code in the layoutSubview. If you want to do anything in the layoutSubview, you have to subclass that method to override it when you need to update the subview frame
LayoutSubviews Analysis
- Init initialization does not trigger layoutSubviews.
- AddSubview triggers layoutSubviews.
If the addSubview is executed twice in a row, it will only be executed once, because after a runLoop is completed, it will be executed once if it needs to be refreshed.
- Changing the Frame of a UIView triggers layoutSubviews
Of course, if the frame value changes before and after setting.
- Scrolling through a UIScrollView triggers a UIView relayout that triggers layoutSubviews.
- Call setNeedsLayout or layoutIfNeeded directly.
In apple’s official documentation
You should override this method only if the autoresizing behaviors of the subviews do not offer the behavior you want.
LayoutSubviews, which is called when we adjust the subview position inside a class. The reverse is true: if you want to set the position of subviews externally, don’t override it.
IOS Layout mechanism related methods
- (CGSize)sizeThatFits:(CGSize)size - (void)sizeToFit ——————- - (void)layoutSubviews - (void)layoutIfNeeded - SetNeedsLayout —————— - - (void)setNeedsDisplay - (void)drawRectCopy the code
Refresh the child object layout
-
LayoutSubviews method: This method, by default, does nothing and needs to be overridden by subclasses
-
SetNeedsLayout method: mark the need for a new layout and asynchronously call layoutIfNeeded to refresh the layout, not immediately, but layoutSubviews must be called
-
LayoutIfNeeded method: If there are tags that need to be refreshed, call layoutSubviews immediately for layout (if there are no tags, layoutSubviews will not be called)
To refresh immediately, call [View setNeedsLayout], set the tag to need layout, and then call [View layoutIfNeeded] immediately to make layout always “need to refresh” until the view is first displayed. You can call [View layoutIfNeeded] directly