我试图遍历一个数组,一次点亮一种颜色,一旦完成循环遍历每个项目,调用另一个函数运行。到目前为止我有这个:
//Delay function from http://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
@IBAction func computerTurn(){
if(isFirstLevel){levelLabel.text = ("Level 1"); isFirstLevel = false}
else{ level++ }
var gameOrderCopy = gameOrder
var randomNumber = Int(arc4random_uniform(4))
gameOrder.append(randomNumber)
var i = 0
for number in gameOrder{
if number == 0{
self.greenButton.highlighted = true
self.delay(1){
self.greenButton.highlighted = false
}
}
else if number == 1{
self.redButton.highlighted = true
self.delay(1){
self.redButton.highlighted = false
}
}
else if number == 2{
self.yellowButton.highlighted = true
self.delay(1){
self.yellowButton.highlighted = false
}
}
else if number == 3{
self.blueButton.highlighted = true
self.delay(1){
self.blueButton.highlighted = false
}
}
}
}
但此刻,它所做的只是延迟一秒钟,然后立即点亮所有颜色。我需要的是按顺序点亮颜色,每次之间有第二个延迟。提前谢谢!
答案 0 :(得分:3)
不要拖延1,将var delayTime = 1
放在循环上方,然后在循环中执行self.delay(delayTime++)
答案 1 :(得分:1)
您可以尝试以下两种方法之一:
一:在sleep(1)
的迭代开始时插入gameOrder
。
二:稍微修改delay
功能
func delay(delay:UInt32, closure:()->()) {
sleep(delay)
closure()
}