【问题标题】:UIView.animateWithDuration swift loop animationUIView.animateWithDuration 快速循环动画
【发布时间】:2015-02-23 23:12:42
【问题描述】:

在 ViewController.Swift 中,我设法让一个盒子从一个点到另一个点进行动画处理。我认为循环这个很容易,所以盒子会动画到一个点,然后动画回到它的原始位置,然后再次循环。我设法将对象移动到一个位置并在“完成”中再次将其移回,但这不会使 i 循环。如何实现?

我认为这可能可行,但老实说我不知道​​:

let boxmoves = [CGRect(x: 120, y: 220, width: 100, height: 100), CGRect(x: 120, y: 120, width: 100, height: 100)]
for boxmove in boxmoves {
    coloredSquare.frame = boxmove
}

如何根据设备宽度将其居中(我假设涉及一些数学运算?)?

我的代码:

let coloredSquare = UIView()

coloredSquare.backgroundColor = UIColor.blueColor()

coloredSquare.frame = CGRect(x: 120, y: 120, width: 100, height: 100)

self.view.addSubview(coloredSquare)

// found repeate but this will not animate as I want.
//UIView.animateWithDuration(2.0, delay: 0.2, options: UIViewAnimationOptions.Repeat, animations: {
UIView.animateWithDuration(2.0, animations: {

    coloredSquare.frame = CGRect(x: 120, y: 220, width: 100, height: 100)

    }, completion: { finished in
        UIView.animateWithDuration(2.0, animations: {
        coloredSquare.frame = CGRect(x: 120, y: 120, width: 100, height: 100)
        })
})

【问题讨论】:

    标签: ios swift uikit core-animation uiviewanimation


    【解决方案1】:
    UIView.animate(withDuration: 3.0,
                               delay: 0.0,
                               options: [.curveLinear, .repeat],
                               animations: { () -> Void in
                               coloredSquare.frame = CGRect(x: 120, y: 220, width: 100, height: 100)
    
    }, completion: { (finished: Bool) -> Void in
    
    })
    

    【讨论】:

      【解决方案2】:

      不需要做完成块的方法,只需使用动画选项参数即可:

      为 Swift 3.0 更新

      UIView.animate(withDuration: 2.0, delay: 0, options: [.repeat, .autoreverse], animations: {
      
          coloredSquare.frame = CGRect(x: 120, y: 220, width: 100, height: 100)
      
      }, completion: nil)
      

      如果出于任何原因您想稍后停止动画,只需使用:

      coloredSquare.layer.removeAllAnimations()
      

      【讨论】:

      • 哇,就这么简单。谢谢@Mazyod!你知道如何根据设备宽度居中吗?
      • @JohanNdiyoLinnarsson 好吧,显然,您必须删除所有这些硬编码值。尝试将框架设置为您想要的大小,然后为 coloredSquare.center 属性设置动画,而不是框架。要在视图中居中,请尝试coloredSquare.center = view.center,或者更好的是coloredSquare.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
      • 如果您不使用自动布局,您还需要将autoresizingMask 属性设置为灵活边距。
      • 感谢您的帮助@Mazyod。在您的帮助下,我设法解决了我的问题。
      • @Blankarsch coloredSquare.layer.removeAllAnimations()
      猜你喜欢
      • 2016-01-16
      • 1970-01-01
      • 2014-11-24
      • 2016-10-14
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2020-02-17
      • 2017-03-03
      相关资源
      最近更新 更多