Swift:for循环中延迟的动画不起作用?
Posted
技术标签:
【中文标题】Swift:for循环中延迟的动画不起作用?【英文标题】:Swift: Animation with delay in for loop not working? 【发布时间】:2017-02-20 18:44:21 【问题描述】:好的,我查看了大量其他帖子,但是我的方法不起作用。我有一系列图像(2-7.png),我试图连续制作动画,每个图像之间都有延迟。为此,我有:
for i in 2...7
//code that runs after the transition is complete here
var bubView = UIImageView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
bubView.image = UIImage(named: "\(i).png")
//bubView.backgroundColor = UIColor.black
bubView.center = CGPoint(x: bubView.center.x, y: self.bounds.height * 0.69)
self.addSubview(bubView)
UIView.animate(withDuration: 0.4, delay: 2.0, usingSpringWithDamping:
0.6, initialSpringVelocity: 1.25, options: [], animations:
//thing being animated
bubView.frame = CGRect(x: 0, y: 0, width: self.screenSize.width, height: self.screenSize.width)
bubView.center = CGPoint(x: bubView.center.x, y: self.bounds.height * 0.69)
, completion: finished in
)
我也尝试过在动画中不延迟,只是在 for 循环开始时坚持延迟,但是这样所有图像都会立即动画。都是延迟2s,然后都进来了。
如何单独延迟每一个?
【问题讨论】:
【参考方案1】:您为它们提供了相同的动画,因此它们都同时发生。如果您希望它们分别制作动画,请尝试以下操作:
设置延迟:为 2.0*Double(i)
【讨论】:
【参考方案2】:您同时设置所有动画。为了实现您想要的,您可以根据 Gaston 提到的 i
设置延迟或创建递归函数
func animateView(startWithView : Int = 2)
//code that runs after the transition is complete here
var bubView = UIImageView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
bubView.image = UIImage(named: "\(startWithView).png")
//bubView.backgroundColor = UIColor.black
bubView.center = CGPoint(x: bubView.center.x, y: self.bounds.height * 0.69)
self.addSubview(bubView)
UIView.animate(withDuration: 0.4, delay: 2.0, usingSpringWithDamping:
0.6, initialSpringVelocity: 1.25, options: [], animations:
//thing being animated
bubView.frame = CGRect(x: 0, y: 0, width: self.screenSize.width, height: self.screenSize.width)
bubView.center = CGPoint(x: bubView.center.x, y: self.bounds.height * 0.69)
, completion: finished in
if startWithView < 7
animateView(startWithView: startWithView + 1)
)
然后调用
animateView()
考虑更改输入,使其更易于重用。 我会采用这种解决方案,但 Gaston 的解决方案更容易实施。
【讨论】:
以上是关于Swift:for循环中延迟的动画不起作用?的主要内容,如果未能解决你的问题,请参考以下文章
swift - 从 var(UITextField 输入)中删除空格不起作用