Search code examples
iosobjective-cautolayoutnslayoutconstraint

animating autolayout `leftAnchor` constraint change


I have a UIView which I am initializing to start 'offscreen' at the right side of a view taking 100%. I do this via the following:

[childView.leftAnchor constraintEqualToAnchor: superview.rightAnchor
                                     constant: 1.0].active = YES;

I would then like to 'slide' the view in from the left. I thought maybe doing the following:

[UIView animateWithDuration: 5
                 animations: ^{
                     [childView.leftAnchor constraintEqualToAnchor: superview.leftAnchor
                                                               constant: 1.0].active = YES;
                 }];

Might do it, but it happens instantly (no animations, it just 'appears').

Is it possible to use auto layout anchors to provide animations?


Solution

  • [childView.leftAnchor constraintEqualToAnchor: superview.leftAnchor constant: 1.0].active = YES;
    [UIView animateWithDuration: 5
                     animations: ^{
                         [childView layoutIfNeeded];
                     }];
    

    This should do it. The constraint change itself shouldn't be in the animation block, just the layout call. You should also probably disable/remove the initial constraint you made because this new one is in direct conflict with it (you'll probably see a warning in your console).