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 快速循环动画


基础教程推荐
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01