First, the principle of automatic layout

The Layout Engine recalculates the Layout when the view detects the Change, and calls superview.setNeedslayout ().

Use layoutSubviews() to copy a subview frame from the Layout Engine

At this point, the system calculates the frame and then renders it, the same as the handwritten layout

3, Application Run Loop

The Layout Engine cycles through the system RunLoop

When a constraint is changed, the Layout Engine is triggered to calculate the frame of the view, then the Layout is performed from top to bottom, and then the interface is updated in the next run loop.

layoutSubviews

LayoutSubviews are called when:

1.1 View Init initialization does not trigger layoutSubviews

AddSubView does not call layoutSubViews when the View frame is 0.

If the rect value is not CGRectZero, LayoutSubViews of the View will be triggered.

1.2. View calls setLayoutSubViews directly

1.3 child control addSubview will trigger View layoutSubviews; (Most commonly used)

1.4. LayoutSubViews is called when the frame of the child control changes

1.5. When the frame of a View changes, LayoutSubViews of the parent control will be called

1.6. View layoutSubViews will be called when the parent control’s frame changes

1.7. Scrolling a UIScrollView triggers the View’s layoutSubviews

1.8Rotating Screen triggers layoutSubviews (ViewWillLayoutSubView)

drawRect

Override this method to perform the redraw task

DrawRect call mechanism: recommended in 1 and 2 below; However, 3 and 4 do not advocate

2.1. If the recT size is not set during UIView initialization, drawRect will not be called automatically.

2.2. This method is called after sizeThatFits is called, so sizeToFit can be used to calculate size. The drawRect: method is then automatically called;

2.3. Set the contentMode property to UIViewContentModeRedraw. DrawRect is automatically called every time a frame is set or changed;

2.4. Call setNeedsDisplay directly, or setNeedsDisplayInRect: to trigger drawRect:, but only if rect cannot be 0.

sizeToFit

SizeToFit: calculates the optimal size and changes its own size;

SizeThatFits: Computs the optimal size but does not change its size

UIView’s sizeToFit and NSString’s boundingRectWithSize: Options: Attributes: Context: methods are very performance – consuming and not suitable for scenarios where calls are frequent or they may cause a lag.