AutoLayout, Constraints and Animation

后端 未结 3 399
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 04:31

Let\'s assume that I have this UIView:

\"enter

with these relativ

相关标签:
3条回答
  • 2021-01-03 05:06

    For animation you need to change constant of the left and top constraint instead of adding new constraint. As follows:

     self.mBtnTopConstraint.constant = yourval1;
        self.mBtmLeftConstraint.constant = yourval2;
        [yourbtn setNeedsUpdateConstraints];
    
        [UIView animateWithDuration:0.5 animations:^{
    
                [yourbtn layoutIfNeeded];
    
            } completion:^(BOOL isFinished){
            }];
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-03 05:14

    You can make a placeholder UIView with the ending constraints you want and swap the original constraints with the placeholder UIView constraints.

    That way it keeps the layout constraints in the storyboard and keeps your code from being messy. It also gives you the added effect of seeing the end result of your animation in the preview section of xcode.

    If use the cocoapod "SBP" to do this with just a couple lines. Here's a tutorial.

    0 讨论(0)
  • 2021-01-03 05:21

    Delete the left and top constraints, add the bottom and right constraints, then call layoutIfNeeded in an animation block to animate to the new position. The code in the second method, move2 could be embedded in the completion block of move1, but I find it easier to read if you keep the two moves in separate methods (it does necessitate the addition of another property, bottomCon):

    - (IBAction)move1:(UIButton *)sender {
        [sender setTitle:@"Second" forState:UIControlStateNormal];
        [sender layoutIfNeeded];
        [self.view removeConstraints:@[self.leftCon,self.topCon]];
        self.bottomCon = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeBottom relatedBy:0 toItem:self.button attribute:NSLayoutAttributeBottom multiplier:1 constant:20];
        [self.view addConstraint:self.bottomCon];
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeRight relatedBy:0 toItem:self.button attribute:NSLayoutAttributeRight multiplier:1 constant:20]];
        [UIView animateWithDuration:1 delay:1.0 options:0 animations:^{
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            [sender setTitle:@"Third" forState:UIControlStateNormal];
            [self move2];
        }];
    }
    
    -(void)move2 {
        [self.view removeConstraint:self.bottomCon];
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeTop relatedBy:0 toItem:self.button attribute:NSLayoutAttributeTop multiplier:1 constant:-20]];
        [UIView animateWithDuration:1 delay:1.0 options:0 animations:^{
            [self.view layoutIfNeeded];
        } completion:nil];
    }
    
    0 讨论(0)
提交回复
热议问题