Difference between layoutSubviews() and viewWillLayoutSubviews()

10,723

Solution 1

There is no effective difference. One (layoutSubviews) is a message the runtime sends to the view, the other (viewWillLayoutSubviews) is a message the runtime sends to the view controller. The message to the view controller tells the view controller that its view is about to receive the view message! That's all. They go together.

Solution 2

viewWillLayoutSubviews is called when view controller's view's bounds changed (usually happens when view loaded, or orientation changed, or if it's a child view controller, and its view was changed by the parent view controller), but before it's subview's bounds or position changes. You can override this method to make some changes to subview's bounds or position before the view layouts them.

layoutSubviews, from Apple's documentation:

You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want

This method gets called when a layout update happens, either by changing the view's bounds explicitly or call setNeedsLayout or layoutIfNeeded on the view to force a layout update. Please remember that it will be called automatically by the OS, and you should never call it directly. It's quite rare that you need to override this method, cause usually the autoresizing or constraint will do the job for you.

Share:
10,723
Thor
Author by

Thor

Updated on June 15, 2022

Comments

  • Thor
    Thor almost 2 years

    I understand that layoutSubviews() is a method in UIView and viewWillLayoutSubviews() is a method in UIViewController, they are both used to adjust the position of the subviews when the bounds/frame changes, but I'm not exactly sure the difference between them and when to use them. Could someone please enlighten me?