UIView自动布局幻灯片在屏幕或屏幕外动画

时间:2014-08-21 09:51:50

标签: ios autolayout uiviewanimation

我无法弄清楚如何使用自动布局进行幻灯片放入/缩小动画。

我添加这样的约束:

NSDictionary *viewsDic = @{@"tmpView" : tmpView};
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[tmpView]|" options:0 metrics:nil views:viewsDic]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[tmpView]|" options:0 metrics:nil views:viewsDic]];

[UIView animateWithDuration:.4 animations:^{
        [self.view layoutIfNeeded];
    }];

但这动画从0,0位置增长。如何实现幻灯片进/出动画?

1 个答案:

答案 0 :(得分:4)

据我了解,你需要获得移位效果。如果我的假设是正确的,您需要在动画期间手动管理水平或垂直填充。你需要得到关于水平/垂直约束的参考:

@property (nonatomic, strong) NSLayoutConstraint *topPadding;
@property (nonatomic, strong) NSLayoutConstraint *heightConstraint;

添加具有初始值的约束,以使tmpView超出其超级视图的可见部分:

self.heightConstraint = [NSLayoutConstraint constraintWithItem:tmpView
                                               attribute:NSLayoutAttributeHeight
                                               relatedBy:NSLayoutRelationEqual
                                                  toItem:nil
                                               attribute:NSLayoutAttributeNotAnAttribute
                                              multiplier:1.0
                                                constant:0.0];

self.topPadding = [NSLayoutConstraint constraintWithItem:tmpView
                                           attribute:NSLayoutAttributeTop
                                           relatedBy:NSLayoutRelationEqual
                                              toItem:self.view
                                           attribute:NSLayoutAttributeTop
                                          multiplier:1.0
                                            constant:self.view.bounds.size.height];

[self.view addConstraint:self.topPadding];
[self.view addConstraint:self.heightConstraint];

然后我们只需要用动画显示tmpView

 [self.view layoutIfNeeded];

 [UIView animateWithDuration:.4 animations:^{
    self.topPadding.constant = 0.0;
    self.heightConstraint.constant = self.view.bounds.size.height;

    [self.view layoutIfNeeded];
}];

Whit这个例子tmpView从底部出现。 请确保self.topPadding不会与其他约束

冲突

要隐藏视图,您可以使用以下内容:

 [self.view layoutIfNeeded];

 [UIView animateWithDuration:.4 animations:^{
    self.topPadding.constant = self.superview.bounds.size.height;

    [self.view layoutIfNeeded];
}];

UPD。:有时您还需要添加高度限制。在我的示例

中添加了self.heightConstraint的使用

UPD。:您仍需要水平约束。 请留下以下几行:

NSDictionary *viewsDic = @{@"tmpView" : tmpView};
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[tmpView]|" options:0 metrics:nil views:viewsDic]];