在for循环中使用延迟 - Swift

时间:2016-03-14 18:09:21

标签: swift for-loop delay

我试图创建一个简单的启动应用程序来学习Swift。我是一般的编程新手,我有点过头了。这段代码用于突出显示(更改某个UIButton的背景颜色),然后将其更改回来。起初我为每个动作添加了0.5秒的延迟,但后来我在执行结束时学会了一次IBAction更新?所以我随后添加了每次递增的延迟。该代码适用于前3个或4个循环,但随后会起作用并且不会正确延迟。请帮忙,谢谢

func SSSays(clicks:Int) {

    sPattern.append(Int(arc4random_uniform(4) + 1))
    var wait = 0.5


    for button in sPattern {

        if(button == 1) {
            wait = wait + 0.5
            self.delay(wait) {self.BBB.backgroundColor = UIColor.init(red: (102/255), green: (178/255), blue: (255/255), alpha: (1))}

            wait = wait + 0.5
            self.delay(wait) { self.BBB.backgroundColor = UIColor.blueColor() }


        } else if(button == 2) {

            wait = wait + 0.5
            self.delay(wait) {self.RBB.backgroundColor = UIColor.init(red: (255/255), green: (153/255), blue: (153/255), alpha: (1))}

            wait = wait + 0.5
            self.delay(wait) {self.RBB.backgroundColor = UIColor.redColor() }


        } else if(button == 3){

            wait = wait + 0.5
            self.delay(wait) {self.GBB.backgroundColor = UIColor.init(red: (153/255), green: (255/255), blue: (204/255), alpha: (1)) }

            wait = wait + 0.5
            self.delay(wait) {self.GBB.backgroundColor = UIColor.greenColor() }


        } else if(button == 4){

            wait = wait + 0.5
            self.delay(wait) {self.OBB.backgroundColor = UIColor.init(red: (255/255), green: (204/255), blue: (255/255), alpha: (1)) }
            wait = wait + 0.5
            self.delay(wait) {self.OBB.backgroundColor = UIColor.magentaColor() }

        }
    }



}




func delay(delay:Double, closure:()->()) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(delay * Double(NSEC_PER_SEC))),dispatch_get_main_queue(), closure)
}

1 个答案:

答案 0 :(得分:2)

我建议您研究一下动画功能。它们是出于这个原因而创建的,它将大大简化您的代码。这是一个基本的,你可以玩,以帮助你开始:

UIView.animateWithDuration(1.0, delay: 0.0, options: [], animations: {
            self.BBB.backgroundColor = UIColor.redColor()
            }, completion: nil)

Swift 4.0

UIView.animate(withDuration: 1.0, delay: 0.0, options:.allowAnimatedContent, animations: {
                self.BBB.backgroundColor = .red
            }, completion: nil)

然后,如果您认为合适,则可以在完成动画的持续时间后,为完成块添加代码以处理其他代码。

options: []可以使用自动反转,重复等参数来为您提供额外的效果。