UIView.animateWithDuration快速循环动画 [英] UIView.animateWithDuration swift loop animation
问题描述
在ViewController.Swift中,我设法将一个框从一个点设置为另一个点。我认为循环这很容易,所以框会动画到一个点,然后动画回到原来的位置,然后再循环。我已设法将对象移动到一个位置并在完成中再次将其移回,但这并不会使我循环。怎么能实现呢?
In ViewController.Swift I managed to make a box animate from one point to another. 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?)?
我的代码:
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:
为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.animateWithDuration快速循环动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!