When the application starts, it opens a Runloop, which handles events and view-based page updates. After the event is processed, it returns to runloop, which becomes the view update cycle.

SetNeedsLayout: While the event is being processed, the view update operation is not performed immediately and waits for the next update cycle to update the view (that is, asynchronously). Note: When we modify a frame or constraint, the system automatically flags the layout for recalculation. It triggers the LayoutSubView method.

LayoutIfNeeded: Forces the view to update its layout immediately, which is synchronous execution. When using Auto Layout, the Layout engine updates the position of the view as constraints change. The recipient of this method will be the root view, and the layout will start from the root view of the view tree. If there are no layout updates waiting to be processed, this method simply exits without modifying the layout or calling any layout-related methods.

Animation: Click button: 2 seconds view height slowly from 20 to 100.

- (void)viewDidLoad { [self.view addSubview:self.blueView]; [self.blueView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.mas_equalTo(30.);  make.right.mas_equalTo(-30.); make.top.mas_equalTo(100); make.height.mas_equalTo(20); }]; } - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; NSLog(@"%s",__func__); } - (void)jumpToLogin:(UIButton*)btn { [self.view layoutIfNeeded]; // force an update that was not previously updated. [self.blueView mas_updateConstraints:^(MASConstraintMaker *make) { make.height.mas_equalTo(100); }]; [UIView animateWithDuration:1 animations:^{[self.view layoutIfNeeded]; }]; }Copy the code

Reference: setNeedsLayout vs layoutIfNeeded Explained

SetNeedsLayout VS layoutIfNeeded