1018

我正在用一个更新旧的应用程序,AdBannerView当没有广告时,它会滑出屏幕。当有广告时,它会在屏幕上滑动。基本的东西。

旧样式,我将帧设置在动画块中。新样式,我有一个IBOutlet确定Y位置的自动布局约束,在这种情况下它是距超级视图底部的距离,并修改常量:

- (void)moveBannerOffScreen {
    [UIView animateWithDuration:5 animations:^{
        _addBannerDistanceFromBottomConstraint.constant = -32;
    }];
    bannerIsVisible = FALSE;
}

- (void)moveBannerOnScreen {
    [UIView animateWithDuration:5 animations:^{
        _addBannerDistanceFromBottomConstraint.constant = 0;
    }];
    bannerIsVisible = TRUE;
}

横幅移动,完全符合预期,但没有动画。


更新:我重新观看了WWDC 12 演讲“掌握自动布局的最佳实践”,其中涵盖了动画。它讨论了如何使用CoreAnimation更新约束:

我尝试使用以下代码,但得到完全相同的结果:

- (void)moveBannerOffScreen {
    _addBannerDistanceFromBottomConstraint.constant = -32;
    [UIView animateWithDuration:2 animations:^{
        [self.view setNeedsLayout];
    }];
    bannerIsVisible = FALSE;
}

- (void)moveBannerOnScreen {
    _addBannerDistanceFromBottomConstraint.constant = 0;
    [UIView animateWithDuration:2 animations:^{
        [self.view setNeedsLayout];
    }];
    bannerIsVisible = TRUE;
}

附带说明一下,我已经检查了很多次,这是在线程上执行的。

4

12 回答 12

1776

两个重要说明:

  1. 您需要layoutIfNeeded在动画块内调用。苹果实际上建议你在动画块之前调用一次,以确保所有待处理的布局操作都已完成

  2. 您需要在父视图(例如self.view)上专门调用它,而不是在附加了约束的子视图上调用它。这样做将更新所有受约束的视图,包括为可能被约束到您更改约束的视图的其他视图设置动画(例如,视图 B 附加到视图 A 的底部,而您刚刚更改了视图 A 的顶部偏移量并且您想要视图 B用它制作动画)

试试这个:

Objective-C

- (void)moveBannerOffScreen {
    [self.view layoutIfNeeded];

    [UIView animateWithDuration:5
        animations:^{
            self._addBannerDistanceFromBottomConstraint.constant = -32;
            [self.view layoutIfNeeded]; // Called on parent view
        }];
    bannerIsVisible = FALSE;
}

- (void)moveBannerOnScreen { 
    [self.view layoutIfNeeded];

    [UIView animateWithDuration:5
        animations:^{
            self._addBannerDistanceFromBottomConstraint.constant = 0;
            [self.view layoutIfNeeded]; // Called on parent view
        }];
    bannerIsVisible = TRUE;
}

斯威夫特 3

UIView.animate(withDuration: 5) {
    self._addBannerDistanceFromBottomConstraint.constant = 0
    self.view.layoutIfNeeded()
}
于 2012-09-30T19:00:58.860 回答
117

我很欣赏提供的答案,但我认为更进一步会很好。

文档中的基本块动画

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

但实际上这是一个非常简单的场景。如果我想通过该 updateConstraints方法为子视图约束设置动画怎么办?

调用子视图 updateConstraints 方法的动画块

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

updateConstraints 方法在 UIView 子类中被重写,并且必须在方法结束时调用 super。

- (void)updateConstraints
{
    // Update some constraints

    [super updateConstraints];
}

AutoLayout Guide有很多不足之处,但值得一读。我自己将其用作 a 的一部分,UISwitch它使用一对UITextField带有简单而微妙的折叠动画(0.2 秒长)的 s 来切换子视图。如上所述,子视图的约束在 UIView 子类 updateConstraints 方法中处理。

于 2014-01-22T00:35:50.280 回答
81

通常,您只需要更新约束并layoutIfNeeded在动画块内调用。这可以是更改.constantan 的属性NSLayoutConstraint、添加删除约束 (iOS 7) 或更改.active约束的属性 (iOS 8 和 9)。

示例代码:

[UIView animateWithDuration:0.3 animations:^{
    // Move to right
    self.leadingConstraint.active = false;
    self.trailingConstraint.active = true;

    // Move to bottom
    self.topConstraint.active = false;
    self.bottomConstraint.active = true;

    // Make the animation happen
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
}];

示例设置:

Xcode Project 示例动画项目。

争议

关于是否应该在动画块之前或内部更改约束存在一些问题(请参阅之前的答案)。

以下是教 iOS 的 Martin Pilkington 和编写 Auto Layout 的 Ken Ferry 之间的 Twitter 对话。Ken 解释说,虽然在动画块之外更改常量目前可能有效,但这并不安全,它们确实应该在动画块 内进行更改。https://twitter.com/kongtomorrow/status/440627401018466305

动画片:

示例项目

这是一个简单的项目,展示了如何为视图设置动画。它使用 Objective C 并通过更改.active几个约束的属性来为视图设置动画。 https://github.com/shepting/SampleAutoLayoutAnimation

于 2015-11-13T00:33:16.050 回答
41
// Step 1, update your constraint
self.myOutletToConstraint.constant = 50; // New height (for example)

// Step 2, trigger animation
[UIView animateWithDuration:2.0 animations:^{

    // Step 3, call layoutIfNeeded on your animated view's parent
    [self.view layoutIfNeeded];
}];
于 2013-12-23T14:29:37.213 回答
31

斯威夫特 4 解决方案

UIView.animate

三个简单的步骤:

  1. 更改约束,例如:

    heightAnchor.constant = 50
    
  2. 告诉容器view它的布局是脏的,并且自动布局应该重新计算布局:

    self.view.setNeedsLayout()
    
  3. 在动画块中告诉布局重新计算布局,相当于直接设置帧(在这种情况下自动布局将设置帧):

    UIView.animate(withDuration: 0.5) {
        self.view.layoutIfNeeded()
    }
    

完成最简单的例子:

heightAnchor.constant = 50
self.view.setNeedsLayout()
UIView.animate(withDuration: 0.5) {
    self.view.layoutIfNeeded()
}

边注

有一个可选的第 0 步 - 在更改您可能想要调用的约束之前,self.view.layoutIfNeeded()以确保动画的起点来自应用了旧约束的状态(以防有一些其他不应该包含在动画中的约束更改):

otherConstraint.constant = 30
// this will make sure that otherConstraint won't be animated but will take effect immediately
self.view.layoutIfNeeded()

heightAnchor.constant = 50
self.view.setNeedsLayout()
UIView.animate(withDuration: 0.5) {
    self.view.layoutIfNeeded()
}

UIViewPropertyAnimator

由于在 iOS 10 中我们获得了新的动画机制 - UIViewPropertyAnimator,我们应该知道基本上相同的机制适用于它。步骤基本相同:

heightAnchor.constant = 50
self.view.setNeedsLayout()
let animator = UIViewPropertyAnimator(duration: 0.5, timingParameters: UICubicTimingParameters(animationCurve: .linear))
animator.addAnimations {
    self.view.layoutIfNeeded()
}
animator.startAnimation()

由于animator是对动画的封装,我们可以一直引用它,稍后调用。然而,由于在动画块中我们只是告诉自动布局重新计算帧,我们必须在调用之前更改约束startAnimation。因此,这样的事情是可能的:

// prepare the animator first and keep a reference to it
let animator = UIViewPropertyAnimator(duration: 0.5, timingParameters: UICubicTimingParameters(animationCurve: .linear))
animator.addAnimations {
    self.view.layoutIfNeeded()
}

// at some other point in time we change the constraints and call the animator
heightAnchor.constant = 50
self.view.setNeedsLayout()
animator.startAnimation()

更改约束和启动 animator 的顺序很重要 - 如果我们只是更改约束并将 animator 留到稍后的某个时间点,下一个重绘周期可以调用自动布局重新计算,并且更改不会被动画化。

另外,请记住,单个动画师是不可重复使用的——一旦你运行它,你就不能“重新运行”它。所以我想没有一个很好的理由让动画师留在身边,除非我们用它来控制交互式动画。

于 2018-02-16T11:09:32.773 回答
17

快速解决方案:

yourConstraint.constant = 50
UIView.animate(withDuration: 1.0, animations: {
    yourView.layoutIfNeeded
})
于 2016-08-11T08:42:41.200 回答
16

故事板、代码、提示和一些陷阱

其他答案都很好,但这个答案使用最近的一个例子突出了一些相当重要的动画约束的陷阱。在我意识到以下几点之前,我经历了很多变化:

将您想要定位的约束设置为类变量以保持强引用。在 Swift 中,我使用了惰性变量:

lazy var centerYInflection:NSLayoutConstraint = {
       let temp =  self.view.constraints.filter({ $0.firstItem is MNGStarRating }).filter ( { $0.secondItem is UIWebView }).filter({ $0.firstAttribute == .CenterY }).first
        return temp!
}()

经过一些实验后,我注意到必须从定义约束的两个视图上方的视图(也称为超级视图)中获取约束。在下面的示例中(MNGStarRating 和 UIWebView 都是我在它们之间创建约束的两种类型的项目,它们是 self.view 中的子视图)。

过滤器链接

我利用 Swift 的过滤器方法来分离将用作拐点的所需约束。一个也可能变得更复杂,但过滤器在这里做得很好。

使用 Swift 动画约束

Nota Bene - 此示例是情节提要/代码解决方案,并假设已在情节提要中设置了默认约束。然后可以使用代码对更改进行动画处理。

假设您创建了一个属性以使用准确的标准进行过滤并到达动画的特定拐点(当然,如果您需要多个约束,您也可以过滤数组并循环遍历):

lazy var centerYInflection:NSLayoutConstraint = {
    let temp =  self.view.constraints.filter({ $0.firstItem is MNGStarRating }).filter ( { $0.secondItem is UIWebView }).filter({ $0.firstAttribute == .CenterY }).first
    return temp!
}()

……

一段时间以后...

@IBAction func toggleRatingView (sender:AnyObject){

    let aPointAboveScene = -(max(UIScreen.mainScreen().bounds.width,UIScreen.mainScreen().bounds.height) * 2.0)

    self.view.layoutIfNeeded()


    //Use any animation you want, I like the bounce in springVelocity...
    UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.75, options: [.CurveEaseOut], animations: { () -> Void in

        //I use the frames to determine if the view is on-screen
        if CGRectContainsRect(self.view.frame, self.ratingView.frame) {

            //in frame ~ animate away
            //I play a sound to give the animation some life

            self.centerYInflection.constant = aPointAboveScene
            self.centerYInflection.priority = UILayoutPriority(950)

        } else {

            //I play a different sound just to keep the user engaged
            //out of frame ~ animate into scene
            self.centerYInflection.constant = 0
            self.centerYInflection.priority = UILayoutPriority(950)
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
         }) { (success) -> Void in

            //do something else

        }
    }
}

许多错误的转弯

这些笔记实际上是我为自己写的一组技巧。我个人和痛苦地做了所有不该做的事情。希望本指南可以避免其他人。

  1. 注意 zPositioning。有时当什么都没有发生时,您应该隐藏一些其他视图或使用视图调试器来定位您的动画视图。我什至发现了用户定义的运行时属性在故事板的 xml 中丢失并导致动画视图被覆盖(在工作时)的情况。

  2. 总是花一点时间阅读文档(新旧)、快速帮助和标题。Apple 不断进行大量更改以更好地管理 AutoLayout 约束(请参阅堆栈视图)。或者至少是AutoLayout Cookbook。请记住,有时最好的解决方案是在较旧的文档/视频中。

  3. 使用动画中的值并考虑使用其他 animateWithDuration 变体。

  4. 不要将特定布局值硬编码为确定其他常量更改的标准,而是使用允许您确定视图位置的值。CGRectContainsRect是一个例子

  5. 如果需要,请不要犹豫,使用与参与约束定义的视图关联的布局边距 let viewMargins = self.webview.layoutMarginsGuide:例如
  6. 不要做你不必做的工作,情节提要上所有具有约束的视图都有附加到属性 self.viewName.constraints 的约束
  7. 将任何约束的优先级更改为小于 1000。我在情节提要上将我的设置为 250(低)或 750(高);(如果您尝试将 1000 优先级更改为代码中的任何内容,则应用程序将崩溃,因为需要 1000)
  8. 考虑不要立即尝试使用 activateConstraints 和 deactivateConstraints (它们有它们的位置,但是当只是学习或者如果你正在使用情节提要时,使用这些可能意味着你做的太多了~它们确实有一个位置,如下所示)
  9. 考虑不要使用 addConstraints / removeConstraints ,除非你真的在代码中添加了一个新的约束。我发现大多数时候我在情节提要中使用所需的约束来布局视图(将视图放置在屏幕外),然后在代码中,我为先前在情节提要中创建的约束设置动画以移动视图。
  10. 我花了很多时间来建立新的 NSAnchorLayout 类和子类的约束。这些工作很好,但我花了一段时间才意识到我需要的所有约束都已经存在于情节提要中。如果您在代码中构建约束,那么肯定会使用此方法来聚合您的约束:

使用情节提要时避免使用的快速解决方案示例

private var _nc:[NSLayoutConstraint] = []
    lazy var newConstraints:[NSLayoutConstraint] = {

        if !(self._nc.isEmpty) {
            return self._nc
        }

        let viewMargins = self.webview.layoutMarginsGuide
        let minimumScreenWidth = min(UIScreen.mainScreen().bounds.width,UIScreen.mainScreen().bounds.height)

        let centerY = self.ratingView.centerYAnchor.constraintEqualToAnchor(self.webview.centerYAnchor)
        centerY.constant = -1000.0
        centerY.priority = (950)
        let centerX =  self.ratingView.centerXAnchor.constraintEqualToAnchor(self.webview.centerXAnchor)
        centerX.priority = (950)

        if let buttonConstraints = self.originalRatingViewConstraints?.filter({

            ($0.firstItem is UIButton || $0.secondItem is UIButton )
        }) {
            self._nc.appendContentsOf(buttonConstraints)

        }

        self._nc.append( centerY)
        self._nc.append( centerX)

        self._nc.append (self.ratingView.leadingAnchor.constraintEqualToAnchor(viewMargins.leadingAnchor, constant: 10.0))
        self._nc.append (self.ratingView.trailingAnchor.constraintEqualToAnchor(viewMargins.trailingAnchor, constant: 10.0))
        self._nc.append (self.ratingView.widthAnchor.constraintEqualToConstant((minimumScreenWidth - 20.0)))
        self._nc.append (self.ratingView.heightAnchor.constraintEqualToConstant(200.0))

        return self._nc
    }()

如果您忘记了这些技巧中的一个或更简单的技巧,例如在哪里添加 layoutIfNeeded,很可能什么都不会发生:在这种情况下,您可能会有一个半生不熟的解决方案,如下所示:

注意 - 花点时间阅读下面的 AutoLayout 部分和原始指南。有一种方法可以使用这些技术来补充您的动态动画师。

UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 1.0, options: [.CurveEaseOut], animations: { () -> Void in

            //
            if self.starTopInflectionPoint.constant < 0  {
                //-3000
                //offscreen
                self.starTopInflectionPoint.constant = self.navigationController?.navigationBar.bounds.height ?? 0
                self.changeConstraintPriority([self.starTopInflectionPoint], value: UILayoutPriority(950), forView: self.ratingView)

            } else {

                self.starTopInflectionPoint.constant = -3000
                 self.changeConstraintPriority([self.starTopInflectionPoint], value: UILayoutPriority(950), forView: self.ratingView)
            }

        }) { (success) -> Void in

            //do something else
        }

    }

AutoLayout Guide 中的片段(注意第二个片段用于使用 OS X)。顺便说一句-据我所知,这不再在当前指南中。 首选技术不断发展。

自动布局所做的动画更改

如果您需要完全控制自动布局所做的动画更改,则必须以编程方式进行约束更改。iOS 和 OS X 的基本概念相同,但有一些细微差别。

在 iOS 应用程序中,您的代码如下所示:

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

在 OS X 中,使用支持图层的动画时使用以下代码:

[containterView layoutSubtreeIfNeeded];
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
     [context setAllowsImplicitAnimation: YES];
     // Make all constraint changes here
     [containerView layoutSubtreeIfNeeded];
}];

当您不使用支持图层的动画时,您必须使用约束的动画器为常量设置动画:

[[constraint animator] setConstant:42];

对于那些在视觉上学习得更好的人,请查看Apple 的这个早期视频

密切关注

通常在文档中会有一些小注释或代码片段会导致更大的想法。例如,将自动布局约束附加到动态动画师是一个好主意。

祝你好运,愿原力与你同在。

于 2015-12-11T01:49:37.490 回答
9

工作解决方案 100% Swift 5.3

我已经阅读了所有答案,并希望分享我在所有应用程序中使用的代码和行的层次结构以正确设置它们的动画,这里的一些解决方案不起作用,你应该在较慢的设备上检查它们,例如 iPhone 5。

self.btnHeightConstraint.constant = 110
UIView.animate(withDuration: 0.27) { [weak self] in 
     self?.view.layoutIfNeeded()
}
于 2017-06-12T08:41:17.343 回答
5

我试图为约束设置动画,但很难找到一个好的解释。

其他答案所说的是完全正确的:您需要致电[self.view layoutIfNeeded];inside animateWithDuration: animations:。然而,另一个重要的一点是为每个NSLayoutConstraint你想要动画的指针。

我在 GitHub 中创建了一个示例

于 2014-11-25T08:24:33.327 回答
4

使用 Xcode 8.3.3 为 Swift 3 工作且刚刚测试过的解决方案:

self.view.layoutIfNeeded()
self.calendarViewHeight.constant = 56.0

UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
        self.view.layoutIfNeeded()
    }, completion: nil)

请记住,self.calendarViewHeight 是一个引用 customView (CalendarView) 的约束。我在 self.view 而不是 self.calendarView 上调用了 .layoutIfNeeded()

希望这有帮助。

于 2017-07-19T12:17:43.800 回答
3

有一篇文章谈论这个: http ://weblog.invasivecode.com/post/42362079291/auto-layout-and-core-animation-auto-layout-was

其中,他这样编码:

- (void)handleTapFrom:(UIGestureRecognizer *)gesture {
    if (_isVisible) {
        _isVisible = NO;
        self.topConstraint.constant = -44.;    // 1
        [self.navbar setNeedsUpdateConstraints];  // 2
        [UIView animateWithDuration:.3 animations:^{
            [self.navbar layoutIfNeeded]; // 3
        }];
    } else {
        _isVisible = YES;
        self.topConstraint.constant = 0.;
        [self.navbar setNeedsUpdateConstraints];
        [UIView animateWithDuration:.3 animations:^{
            [self.navbar layoutIfNeeded];
        }];
    }
}

希望能帮助到你。

于 2013-09-13T08:35:13.060 回答
1

在约束动画的上下文中,我想提一下我在keyboard_opened 通知中立即对约束进行动画处理的特定情况。

约束定义了从文本字段到容器顶部的顶部空间。打开键盘后,我只需将常数除以 2。

我无法直接在键盘通知中实现一致的平滑约束动画。大约一半的时间视图只会跳转到新位置 - 没有动画。

我突然想到,由于键盘打开,可能会发生一些额外的布局。添加一个具有 10 毫秒延迟的简单 dispatch_after 块使动画每次都运行 - 没有跳跃。

于 2016-04-15T15:54:27.237 回答