How do I animate constraint changes?

后端 未结 12 1671
野的像风
野的像风 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:52

    I appreciate the answer provided, but I think it would be nice to take it a bit further.

    The basic block animation from the documentation

    [containerView layoutIfNeeded]; // Ensures that all pending layout operations have been completed
    [UIView animateWithDuration:1.0 animations:^{
         // Make all constraint changes here
         [containerView layoutIfNeeded]; // Forces the layout of the subtree animation block and then captures all of the frame changes
    }];
    

    but really this is a very simplistic scenario. What if I want to animate subview constraints via the updateConstraints method?

    An animation block that calls the subviews updateConstraints method

    [self.view layoutIfNeeded];
    [self.subView setNeedsUpdateConstraints];
    [self.subView updateConstraintsIfNeeded];
    [UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionLayoutSubviews animations:^{
        [self.view layoutIfNeeded];
    } completion:nil];
    

    The updateConstraints method is overridden in the UIView subclass and must call super at the end of the method.

    - (void)updateConstraints
    {
        // Update some constraints
    
        [super updateConstraints];
    }
    

    The AutoLayout Guide leaves much to be desired but it is worth reading. I myself am using this as part of a UISwitch that toggles a subview with a pair of UITextFields with a simple and subtle collapse animation (0.2 seconds long). The constraints for the subview are being handled in the UIView subclasses updateConstraints methods as described above.

提交回复
热议问题