UIView.animateWithDuration快速循环动画
在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
}
如何根据设备宽度居中(我假设涉及数学运算?)?
我的代码:
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)
})
})
回答:
无需执行完成块方法,只需使用animation options参数即可:
已针对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()
以上是 UIView.animateWithDuration快速循环动画 的全部内容, 来源链接: utcz.com/qa/411849.html