在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)
})
})
答案 0 :(得分:100)
无需执行完成块方法,只需使用动画选项参数:
针对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()
答案 1 :(得分:1)
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
})