Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a view is set up in IB with Auto Layout, what happens if you try to change its frame programmatically?

A project I've started helping on did not use Auto Layout before and I'm updating it to use Auto Layout and size classes. There's a decent amount of frame manipulation code throughout the app (e.g. setting frame directly rather than changing constraint constants), and I'm wondering how this affects a view that's been set up with Auto Layout constraints.

I'm working on doing away with the frame-changing portions of code and changing it to update constraint constants where needed, but since I'm not yet 100% familiar with how every piece of the code works, it'd be helpful to have a better understanding of how auto layout and coded frame changes can affect each other so that if a view doesn't appear properly at runtime I can better determine if it's something I set up or perhaps a piece of older code somewhere that needs to be found and updated.

like image 551
bluewraith Avatar asked Mar 21 '16 16:03

bluewraith


1 Answers

It's very simple. You just have to understand what auto layout is.

Here's how it works. The constraints are just a list of instructions; they do not, of themselves, actually do anything at all. There's a system message layoutSubviews, which is sent at moments you do not control — so you should imagine it could be sent any time. When layoutSubviews is actually sent, the constraints are consulted and obeyed (by doing exactly what you would do — that is, the runtime sets the frame, or the bounds and center, of each view).

Thus, you are free to change the frame of a view, but be aware that if layoutSubviews is sent and the constraints disagree with the frame that you set, the view will jump back to where the constraints say to put it.

like image 172
matt Avatar answered Oct 31 '22 21:10

matt