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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With