How do I animate constraint changes?

后端 未结 12 1683
野的像风
野的像风 2020-11-21 23:22

I\'m updating an old app with an AdBannerView and when there is no ad, it slides off screen. When there is an ad it slides on the screen. Basic stuff.

O

12条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 23:49

    Generally, you just need to update constraints and call layoutIfNeeded inside the animation block. This can be either changing the .constant property of an NSLayoutConstraint, adding remove constraints (iOS 7), or changing the .active property of constraints (iOS 8 & 9).

    Sample Code:

    [UIView animateWithDuration:0.3 animations:^{
        // Move to right
        self.leadingConstraint.active = false;
        self.trailingConstraint.active = true;
    
        // Move to bottom
        self.topConstraint.active = false;
        self.bottomConstraint.active = true;
    
        // Make the animation happen
        [self.view setNeedsLayout];
        [self.view layoutIfNeeded];
    }];
    

    Sample Setup:

    Controversy

    There are some questions about whether the constraint should be changed before the animation block, or inside it (see previous answers).

    The following is a Twitter conversation between Martin Pilkington who teaches iOS, and Ken Ferry who wrote Auto Layout. Ken explains that though changing constants outside of the animation block may currently work, it's not safe and they should really be change inside the animation block. https://twitter.com/kongtomorrow/status/440627401018466305

    Animation:

    Sample Project

    Here's a simple project showing how a view can be animated. It's using Objective C and animates the view by changing the .active property of several constraints. https://github.com/shepting/SampleAutoLayoutAnimation

提交回复
热议问题