UIView.animateWithDuration swift loop animation(UIView.animateWithDuration 快速循环动画)
问题描述
在 ViewController.Swift 中,我设法让一个盒子从一个点动画到另一个点.我认为循环这个很容易,所以盒子会动画到一个点,然后动画回到它的原始位置,然后再次循环.我已经设法将对象移动到一个位置并在完成"中再次将其移回,但这不会使 i 循环.如何实现?
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 快速循环动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:UIView.animateWithDuration 快速循环动画


- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01