Issue with UIView Auto Layout Animation

2019-07-22 07:15发布

问题:

I have a UIView that flies from the top when I open that view controller. I've set the Y Constraint of the UIView to -200 and when the view loads, the below is called and everything works fine:

- (void)updateViewConstraints
{
    [super updateViewConstraints];
    self.popUpViewYConstraint.constant = 37.0f;
    self.closeButtonYConstraint.constant = 28.0f;
    [self.popUpBaseView setNeedsUpdateConstraints];
    [self.closeButton setNeedsUpdateConstraints];

    [UIView animateWithDuration:0.25f animations:^{
        [self.popUpBaseView layoutIfNeeded];
        [self.closeButton layoutIfNeeded];
        [self.view layoutIfNeeded];
    }];
}

But now I have a close button that should animate the UIView back to the -200 position and then remove the view controller from the screen. But this animation is not taking place. The view controller is getting removed directly. Here's what I'm doing:

- (IBAction)closePressed:(id)sender
{
    NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
    self.navigationController.viewControllers = navigationArray;

    [UIView animateWithDuration:2.0f animations:^{
        self.popUpViewYConstraint.constant = -200.0f;
        [self.popUpBaseView layoutIfNeeded];
    } completion:^(BOOL finished){
        [navigationArray removeObjectAtIndex: 1];
        [self.baseView removeFromSuperview];
        [self.view removeFromSuperview];
    }];
}

I referred to this link. It seems to be working for them but doesn't work for me. Please help.

回答1:

This line:

self.popUpViewYConstraint.constant = -200.0f;

Should be called before the animation block. Also i'm not sure about hierarchy of your views, but make sure you are calling the correct view with layoutIfNeeded call.



回答2:

How about this

- (IBAction)closePressed:(id)sender
{
    NSMutableArray *navigationArray = [[NSMutableArray alloc]:initWithArray:self.navigationController.viewControllers];
    self.navigationController.viewControllers = navigationArray;

    // I am sure the constant should be set outside the animation block. It won't happen until next run loop, which will be inside the block. 
    self.popUpViewYConstraint.constant = -200.0f;
    // setNeedsUpdateConstraints should be called on the view to which the constraint is added, not the view affected by the constraint.
    [self.baseView setNeedsUpdateConstraints];

    [UIView animateWithDuration:2.0f animations:^{
         // I think this should be topmost view
         [self.view layoutIfNeeded];
    } completion:^(BOOL finished){
        [navigationArray removeObjectAtIndex: 1];
        [self.baseView removeFromSuperview];
        [self.view removeFromSuperview];
    }];
 }