简体   繁体   English

UIView.animateWithDuration快速循环动画

[英]UIView.animateWithDuration swift loop animation

In ViewController.Swift I managed to make a box animate from one point to another. 在ViewController.Swift中,我设法从一个点到另一个点创建一个框。 I thought it would be easy to loop this so the box will animate to one point and then animate back to its original position and then loop again. 我认为循环这很容易,所以框会动画到一个点,然后动画回到原来的位置,然后再循环。 I have managed to move the object to a position and in "complete" move it back again, but that doesn't make i loop. 我已设法将对象移动到一个位置并在“完成”中再次将其移回,但这并不会使我循环。 How can this be achieved? 怎么能实现这一目标?

I thought maybe this could work but i honestly don't know: 我想也许这可行,但老实说我不知道​​:

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
}

How could I center it based on the device-width (I assume there are some math involved?)? 我怎么能根据设备宽度将它居中(我假设涉及一些数学?)?

My code: 我的代码:

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)
        })
})

No need to do the completion block approach, just use the animation options argument: 无需执行完成块方法,只需使用动画选项参数:

updated for Swift 3.0 更新为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)

If for any reason you want to stop the animation later, just use: 如果出于任何原因想要稍后停止动画,只需使用:

coloredSquare.layer.removeAllAnimations()
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

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM