Kodeco Forums

Video Tutorial: Intro to Auto Layout Part 10: Animating Contraints

Learn how the layout system works, how to animate changes to constraints, and which other animation methods you should or should not use with Auto Layout.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3201-auto-layout/lessons/11

Hi. Why don’t you call setNeedsLayout() before layoutIfNeeded? As far as I understand you should notify the system that you need layout (by calling setNeedsLayout()) otherwise layoutIfNeeded() may not relayout views. Or alternatively you may call layoutSubviews() which do not need checking of any flag saying whether layout is needed.

Where am I wrong? Thanks.

Each view internally has a flag that indicates whether it needs layout. If you call setNeedsLayout() it will manually set that flag to true if it hasn’t already. Then, when you call layoutIfNeeded() it will call layoutSubviews() for you, if the flag has been set to true. Finally, layoutSubviews() will perform the layout. Those are the three pieces of the puzzle. However, much of the underlying code for UIView will call setNeedsLayout() automatically. If you do something to the view that it knows will trigger the need for a layout, you don’t have to call it manually. But if you change something that the view doesn’t know impacts layout, you have to call it yourself.

Hi @jerbeers! Thanks for this tutorial, is amazing!

As a personal challenge, I wanted to restore one of the buttons
and I got it. but I want to understand and fix one issue.
when I animated it, the restored button comes from the upper
left corner, how to avoid this behavior? is it related to the frame?

Could you give me some clues so I could understand why is this happening?

Thanks!

When you layout inside an animation block, the animation will start from where the view is now to where it will be in it’s final place. The key is to set “where it is now” first without an animation, and then call layoutIfNeeded() inside the animation block. So, in your example, if you wanted the button to come in from the right, you could set some constraints that position it off the right hand side of the screen and call layoutIfNeeded(). Then adjust the constraints so the button is on screen and call layoutIfNeeded() again, but inside an animation block this time.

1 Like

It works! Thank you very much!

1 Like