Search code examples
core-animationosx-mountain-lionautolayoutnslayoutconstraint

Animating by adding & removing NSLayoutConstraints, instead of adjusting Constants


I have an NSButton whose bottom is flush with its superview's, and I'd like to animate it moving up so that its top is flush with its superview's.

WWDC 2012 Session 228: Best Practices for Mastering Auto Layout mentions two ways to animate layout changes (31:16), and I'm attempting to use the CoreAnimation technique. The example below does correctly move the NSButton, but it does so instantaneously and with no animation.

[button.superview removeConstraint:pointerToBottomSpaceConstraint] ;
NSArray* topSpaceConstraintArray = [NSLayoutConstraint constraintsWithVisualFormat: @"V:|[button]"
                                                                           options: 0
                                                                           metrics: nil
                                                                             views: NSDictionaryOfVariableBindings(button)] ;
[button.superview addConstraints:topSpaceConstraintArray] ;
[NSAnimationContext runAnimationGroup:^(NSAnimationContext* context) {
    context.duration = 2 ;
    context.allowsImplicitAnimation = YES ;
    [button.superview layoutSubtreeIfNeeded] ;
} completionHandler:nil] ;

Can I add & remove NSLayoutConstraints and let CoreAnimation figure out how to animate the change? That seems simpler than me determining the distance between the button's old & new position, then adjusting the NSLayoutConstraint's Constant by that amount.


Solution

  • After adding button.superview.wantsLayer = YES, the above example animates correctly.