UIView.animateWithDuration快速循环动画

Joh*_*son 33 core-animation uikit uiviewanimation ios swift

在ViewController.Swift中,我设法从一个点到另一个点创建一个框.我认为循环这很容易,所以框会动画到一个点,然后动画回到原来的位置,然后再循环.我已设法将对象移动到一个位置并在"完成"中再次将其移回,但这并不会使我循环.怎么能实现这一目标?

我想也许这可行,但老实说我不知道​​:

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
}
Run Code Online (Sandbox Code Playgroud)

我怎么能根据设备宽度将它居中(我假设涉及一些数学?)?

我的代码:

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)
        })
})
Run Code Online (Sandbox Code Playgroud)

Maz*_*yod 118

无需执行完成块方法,只需使用动画选项参数:

更新为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)
Run Code Online (Sandbox Code Playgroud)

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

coloredSquare.layer.removeAllAnimations()
Run Code Online (Sandbox Code Playgroud)

  • @Blankarsch`colouredSquare.layer.removeAllAnimations()` (2认同)