gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:15 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的启动应用程序来学习 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com