UIView自动布局动画问题

时间:2014-01-16 17:35:41

标签: ios iphone objective-c uiview autolayout

当我打开该视图控制器时,我有一个UIView从顶部飞过来。我已将UIView的Y约束设置为-200,当视图加载时,调用以下内容并且一切正常:

- (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];
    }];
}

但是现在我有一个关闭按钮,可以将UIView设置回-200位置,然后从屏幕上移除视图控制器。但这个动画没有发生。视图控制器将被直接删除。这就是我正在做的事情:

- (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];
    }];
}

我提到了this链接。它似乎对他们有用但对我不起作用。 请帮忙。

2 个答案:

答案 0 :(得分:0)

这一行:

self.popUpViewYConstraint.constant = -200.0f;

应该在动画块之前调用。此外,我不确定您的视图的层次结构,但请确保使用layoutIfNeeded调用调用正确的视图。

答案 1 :(得分:0)

这个怎么样

- (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];
    }];
 }