【问题标题】:Animate AutoLayout constraints with different animation curves simultaneously同时使用不同的动画曲线为 AutoLayout 约束设置动画
【发布时间】:2018-04-20 09:16:13
【问题描述】:

如何同时用不同的动画曲线对 AutoLayout 约束进行动画处理?

例如,使用线性曲线为widthAnchorheightAnchor 设置动画,但使用弹簧动画为centerXAnchorcenterYAnchor(在同一视图上)设置动画。 两个动画需要同时执行。

我只知道如何同时为每个人设置动画(在UIView.animate 中调用view.layoutIfNeeded()),但是如何分别为它们设置动画?

【问题讨论】:

    标签: ios swift animation autolayout caanimation


    【解决方案1】:

    你必须执行如下操作:-

    UIView.animate(withDuration: 0.2, animations: {
        //perform animation of height
    }, completion: { _ in
    
        UIView.animate(withDuration: 0.2, animations: {
           //perform animation of width
        }, completion: nil)
    })
    

    如果您想添加一些动画选项,请使用以下代码:--

     UIView.animateWithDuration(0.2, delay: 0.2, options: UIViewAnimationOptions."Set your Animationoption", animations: {
        //perform animation of height
    }, completion: { _ in
    
        UIView.animateWithDuration(0.2, delay: 0.2, options: UIViewAnimationOptions."Set your Animationoption", animations: {
           //perform animation of width
        }, completion: nil)
    })
    

    两者结合:-

      UIView.animateWithDuration(0.2, delay: 0.2, options: UIViewAnimationOptions."Set your Animationoption", animations: {
           //perform animation of width
        }, completion: nil)
    
     UIView.animateWithDuration(0.2, delay: 0.2, options: UIViewAnimationOptions."Set your Animationoption", animations: {
           //perform animation of height
        }, completion: nil)
    

    谢谢。

    【讨论】:

    • 感谢您的回答。但是如果我必须用不同的曲线同时为两者设置动画呢?
    • @V D Purohit AFAIK,您的代码按顺序对widthheight 进行动画处理,对吗?如何将它们两个一起制作动画?
    【解决方案2】:

    您应该尝试创建CABasicAnimations,其中fromValue 设置为每个视图的当前值,然后在没有动画块的情况下调用layoutIfNeeded()。后者将改变视图的框架。如果您在布局步骤之后添加动画,则修改应该是动画的。

    这可能看起来像这样

    let animation1 = CABasicAnimation()
    let animation2 = CABasicAnimation()
    
    animation1.fromValue = view1.center
    animation1... // Set further properties to configure the animation
    animation2.fromValue = ... // Same with second view
    // and so on
    self.view.layoutIfNeeded()
    view1.layer.add(animation1, forKey: "center")
    view2.layer.add(animation2, forKey: ...)
    

    我还没有尝试过,但我很高兴知道它是否有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      相关资源
      最近更新 更多