Search code examples
iosswiftnslayoutconstraint

How to manage constraints of movable views in iOS?


I've a set of buttons which I animate in expand-collapse fashion, more like a drawer open and close action. I simply vary the X positions of these buttons to achieve this and it works fine. While designing this layout in interface builder, I've set the constraints for all these buttons in their 'drawer-closed' state.

Problem arises when the drawer is left open and some other view on the screen gets updated. I understand that viewDidLayoutSubviews() gets called at this instance. Because of this, the drawer menu which was left open closes abruptly messing up with the 'drawer close' animation and the buttons don't get the expected view as in their 'drawer close' state.

I suppose the constraints of the buttons would be getting re-initialized when the viewDidLayoutSubviews() got called.

Now coming to my question - how do we set/manage constraints for views which are going to move runtime because of animations?

I'm a beginner in iOS app development and I did go through questions asked on managing constraints programmatically or viewDidLayoutSubviews etc. but I couldn't find a standard way to follow in the situation I've encountered.

enter image description here


Solution

  • Instead of changing the frame, you could animate the change of constraints.

    Short preview of how to do that:

    yourConstraint.constant = newValue
    
    UIView.animate(withDuration: animationDuration) {
        yourView.layoutIfNeeded()
    }
    

    More information about this can be found here.