2017-04-04 119 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 
        } 
}