【问题标题】:How to animate buttons to travel out of view bounds如何为按钮设置动画以超出视图范围
【发布时间】:2018-12-27 19:02:04
【问题描述】:

在我的主屏幕上,我有一系列居中对齐的按钮:新游戏、如何玩、继续游戏。

单击时,我想为按钮设置动画,使其横向线性地移出屏幕。其中一个按钮(其余的非常相似)具有以下约束(使用自动布局):

Align Center X to: Safe Area
Align Center Y to: Safe Area, Multiplier 1.2
Proportional width 0.6 with Superview
300:50 Ratio: to Button

我认为以下代码可以提供所需的动画,但似乎不起作用:

 button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 1000)
            UIView.animate(withDuration: 1, delay: 1, usingSpringWithDamping: 4, initialSpringVelocity: 4, options: .curveEaseOut, animations: { self.view.layoutIfNeeded()}, completion: nil)

任何关于如何让按钮动画化以使其横向移出屏幕的建议非常感谢!

谢谢

【问题讨论】:

  • 按钮向前动画,它们应该与前导和尾随挂钩,而不是全部使用 centerX,这就是您将控制其中的动画,水平堆栈视图非常适合该动画

标签: swift animation uibutton


【解决方案1】:

就是这样

button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 1000)

将创建另一个约束,并会导致冲突,因此当您创建原始 centerX 时,请将其保存在 var 中

var centerCon:NSLayoutConstraint! 
centerCon = button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 0) 
centerCon.isActive = true

然后玩它的常量值

 centerCon.constant =  1000
 UIView.animate(withDuration: 1, delay: 1, usingSpringWithDamping: 4, initialSpringVelocity: 4, options: .curveEaseOut, animations: { self.view.layoutIfNeeded()}, completion: nil)

【讨论】:

    【解决方案2】:

    这就是我的做法。没有你所有额外的弹性参数,但它可能会有所帮助:

    amountToTranslateBy = self.view.bounds.width // assuming this is executed from inside ViewController
    
    UIView.animate(withDuration: yourDuration, delay: yourDelay, options: .curveEaseOut, animations: {
    
                            for view in yourArrayOfViews {
                                view.center.x -= amountToTranslateBy
                            }
    
                        }, completion: nil)
    

    您设置的约束不应受此动画影响,尤其是因为按钮的约束取决于其他(超级)视图,反之亦然。只要您记得在适当的时间使用相同的方法将视图移回其原始位置 (+= amountToTranslateBy) 就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多