UIView.animateWithDuration Swift循环动画

44

在ViewController.swift中,我成功地让一个方框从一个点移动到另一个点的动画。我认为将其循环应该很容易,让方框动画到一个位置,然后回到原始位置并再次循环。我已经设法将对象移动到一个位置,在“complete”中将其移回,但这并不能使它循环。如何实现这一点?

我想也许这个方法可以奏效,但我真的不确定:

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)
        })
})
2个回答

159

不需要使用完成块的方法,只需使用动画选项参数:

已更新至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()

哇,原来这么简单。谢谢@Mazyod!你知道怎样根据设备宽度居中吗? - JLR
1
@JohanNdiyoLinnarsson 好的,显然你需要删除所有那些硬编码的值。尝试使用所需大小设置框架,然后通过动画coloredSquare.center属性来实现,而不是框架。要将其居中显示在视图中,请尝试coloredSquare.center = view.center,或者更好的是coloredSquare.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY) - Mazyod
如果您没有使用自动布局,您还需要将autoresizingMask属性设置为可伸缩边距。 - Mazyod
感谢您的热心帮助,@Mazyod。在您的帮助下,我成功解决了我的问题。 - JLR
2
coloredSquare.layer.removeAllAnimations() - Mazyod
对于 UIButton 动画:使用 buttonName.imageView?.layer.removeAllAnimations() - Stotch

2
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

})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接