2014-11-01 74 views
1

我试图为我的视图的背景多次动画。例如(当然它需要是动态解决方案)4秒,每秒钟它将从白色变为黑色。我们所期望的: 第二:等到任务完成再次运行之前

  1. 白到黑到白
  2. 白到黑到白
  3. 白到黑到白
  4. 白到黑到白

我试着使用甚至延迟(调度延迟),它将只运行一次 并停止。这是我试过的。

for var index = 0; index < 3; ++index { 
    UIView.animateWithDuration(0.33333, delay: 0.333333, options: UIViewAnimationOptions.CurveEaseIn, animations: {() -> Void in 
     println(elapsedTime) 
     self.view.backgroundColor = UIColor.blackColor() 
    }) { (completed : (Bool)) -> Void in 
     UIView.animateWithDuration(0.333333, animations: {() -> Void in 
      self.view.backgroundColor = UIColor.whiteColor() 
     }) 
    } 
} 

关于如何运行这些命令的任何建议,请等到它们完成并再次运行它们?

回答

1

随着for循环,你基本上设置所有四个动画同时运行。如果你做的是动画代码的功能,你可以从完成块递归调用它的白色动画:

func animateBackground(times: Int) { 
    if times == 0 { return } 

    let blackAnimation = { self.view.backgroundColor = UIColor.blackColor() } 
    let whiteAnimation = { self.view.backgroundColor = UIColor.whiteColor() } 
    UIView.animateWithDuration(0.33333, delay: 0.333333, options: UIViewAnimationOptions.CurveEaseIn, animations: blackAnimation) { 
     completedBlack in // completion block 1 

     UIView.animateWithDuration(0.333333, animations: whiteAnimation) { 
      completedWhite in // completion block 2 
      self.animateBackground(times - 1) 
     } 
    } 
} 

而初始呼叫的样子:

animateBackground(4) 
+0

不知道为什么它击碎,主题1:SIGABRT信号,我认为我没有实现它,我只是复制粘贴功能,并在像你这样的按钮操作中调用它,为什么它会被破坏? – 2014-11-01 16:02:25

+0

只是注意到我没有标记你的答案,对不起! – 2015-06-05 00:42:41

+0

@roimulia可能是因为你在前一个动画的回调中调用了UIView方法,我对此很陌生,但是......我认为如果动画运行在后台线程上,那可能会导致问题。尝试将代码包装到主队列中 – DiogoNeves 2015-09-02 11:37:04

相关问题