Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between layoutSubviews() and viewWillLayoutSubviews()

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?

like image 878
Thor Avatar asked Sep 21 '16 01:09

Thor


2 Answers

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.

like image 50
matt Avatar answered Nov 13 '22 08:11

matt


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.

like image 26
Eric Qian Avatar answered Nov 13 '22 07:11

Eric Qian