ios UIView.animateWithDuration 快速循环动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27660540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:08:41  来源:igfitidea点击:

UIView.animateWithDuration swift loop animation

iosswiftuikitcore-animationuiviewanimation

提问by Johan Ndiyo Linnarsson

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?

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

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

回答by Mazyod

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

回答by niku

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

})