swift - 在 for 循环中使用延迟 -- Swift

标签 swift for-loop delay

我正在尝试制作一个简单的启动应用程序来学习 Swift。总的来说,我是编程新手,而且有点不知所措。这段代码用于突出显示(更改背景颜色)某个 UIButton,然后将其改回。起初我为每个 Action 添加了 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)
}

最佳答案

我建议你研究一下动画函数。它们是出于这个原因而创建的,将大大简化您的代码。这是您可以开始使用的基本方法:

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)

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

选项:[] 可以采用 Autoreverse、Repeat 等参数来为您提供额外的效果。

关于swift - 在 for 循环中使用延迟 -- Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35994897/

相关文章:

r - 从单个州列创建美国地区的虚拟列

c# - 每次跳过20个项目的for循环

delay - 平均互联网延迟

ios - 仅适用于数字类型的通用类型约束

cocoa - 如何禁用 NSScrollView 的水平滚动?

ios - Swift tableView 和prepareForSegue 函数

c - for 循环中的哪个变量的新用户输入

objective-c - 计时器因调整窗口大小而延迟

java - 在 Java 中,如何在特定时间后(可靠地)从主线程中断线程?

swift - 将 SKSpriteNode 移动到触摸的位置