我试图用三种不同的颜色每隔30秒更改UIview的背景颜色,直到条件失败(循环)。以下是我的代码。它工作正常但导致延迟。
斯威夫特3:
DispatchQueue.global(qos: .background).async {
while x < y {
DispatchQueue.main.async() {
self.view.backgroundColor = UIColor(hexString:hexValue[self.currentColorIndex!])
}
Thread.sleep(forTimeInterval: 30.0)
}
}
答案 0 :(得分:0)
我想建议这个解决方案,不完美,我想。对于3种颜色,它可以工作,您应该学习更多Timer
或创建一些for-loop
func changeColor() {
if x < y {
self.view.backgroundColor = UIColor(hexString:hexValue[0])
DispatchQueue.main.asyncAfter(deadline: .now() + 30, execute: { [weak self] in
self?.view.backgroundColor = UIColor(hexString:hexValue[1])
DispatchQueue.main.asyncAfter(deadline: .now() + 30, execute: { [weak self] in
self?.view.backgroundColor = UIColor(hexString:hexValue[2])
DispatchQueue.main.asyncAfter(deadline: .now() + 30, execute: { [weak self] in
self?.changeColor()
})
})
})
}
}
答案 1 :(得分:0)
如下:
func changeColor(newIndex: Int) {
func next(_ index: Int) -> Int {
return Int(Double(index + 1).truncatingRemainder(dividingBy: hexValue.count - 1))
}
guard x < y else { return }
self.view.backgroundColor = UIColor(hexString: hexValue[newIndex])
DispatchQueue.main.asyncAfter(deadline: .now() + 30) {
self.changeColor(newIndex: next(newIndex))
}
}
请注意如何在阵列中添加/删除任意数量的颜色,而无需更改此代码:)
在第一次通话时,您应该使用参数0(或您想要开头的任何其他颜色)来调用changeColor(newIndex: 0)
答案 2 :(得分:0)
这是我的实际代码:
DispatchQueue.global(qos: .background).async {
while self.loopStartTime! < Int64(ed_time){
DispatchQueue.main.asyncAfter(deadline: .now()) {
self.view.backgroundColor = UIColor(hexString: hexValue[self.currentColorIndex!])
}
Thread.sleep(forTimeInterval: self.loop!)
if self.loop != 3.0{
self.loopStartTime = self.loopStartTime! + Int64((self.loop!*1000))
}
else{
self.loopStartTime = self.loopStartTime! + addedTime
}
self.currentColorIndex = self.currentColorIndex! + 1
if self.currentColorIndex! >= hexValue.count{
self.currentColorIndex = 0
}
self.loop = 3.0
}
}