2017-04-04 114 views
0

我试图用三种不同的颜色每30秒更改UIview的背景颜色,直到条件失败(while循环)。以下是我的代码。它工作正常,但造成延迟。用三种颜色每30秒更改视图颜色

斯威夫特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) 
    } 
} 
+2

不要把你的应用程序睡觉 –

回答

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() 
       }) 
      }) 
     }) 
    } 
} 
+0

INTIAL显色指数不为零完全取决于应用程序的time..it改变使用DispatchQueue.main开始时间 – Prani

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)

+0

。 asyncAfter(截止日期:.now()+ 30),它的初始延迟时间为30秒,线程不会被杀死以显示下一个颜色。它永远持续显示相同的颜色。 – Prani

+0

我的不好,我忘了更改一行代码(刚刚更新) –

+0

调度用于第二次再次调用func,当您调用该函数时,更改颜色将立即完成。 –

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 
        } 
}