2016-08-17 77 views
1

我試圖根據陣列[0,1,1,0,0,1,1,0](黑色 - 白色其1)或(白色 - 黑色0)中的位閃爍iPhone屏幕(UIView的背景顏色)。根據陣列中的位閃爍/閃爍UIView

但我無法弄清楚如何在動畫中使用循環和條件。

不工作密碼

Byte u = 65; 
self.myBlock.backgroundColor = [UIColor blackColor]; 

int i = 0; 

[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration:0.4]; 
[UIView setAnimationRepeatCount:8.0]; 
[UIView setAnimationRepeatAutoreverses:NO]; 


if (((u >> i) & 1) == 1) { 
    self.myBlock.backgroundColor = [UIColor blackColor]; 
    self.myBlock.backgroundColor = [UIColor whiteColor]; 
    printf("1"); 
} else { 
    self.myBlock.backgroundColor = [UIColor whiteColor]; 
    self.myBlock.backgroundColor = [UIColor blackColor]; 
    printf("0"); 
} 
i++; // how it can be increased ? 


[UIView commitAnimations]; 

有什麼建議?

+0

嗨德米特里,並歡迎堆棧溢出。你能否擴展你的問題,描述當你嘗試你認爲不工作的代碼時出了什麼問題? –

+0

只學習如何在動畫中使用循環和條件。在我的代碼var我沒有增加。編譯器做所有的計算和在UIview中我只看到它的最終結果。 我認爲這個塊 [UIView beginAnimations:nil context:nil]; [UIView commitAnimations]; 像循環一樣工作。 – Dmitry

回答

0

我爲swift道歉,但轉換爲objective-c應該是微不足道的。你可以使用像這樣的遞歸函數來實現你想要的功能。

我們宣佈數組:

let colors = [0,1,1,0,1,1,0] 

我們的遞歸函數應該是這樣的:

/** 
    Cyle the background color based on bit array. 

    - parameter indicies: An array where the first item is our start index of color array. Second item is the number of times we want the animation to iterate through completely. 
    */ 
    func cycleColors(indicies: [Int]) { 

     // Our current index in the colors array 
     var currentArrayIndex = indicies[0] 

     // Our current index in number of full cycles through the color array we've completed 
     var fullInterations = indicies[1] 

     // We cycle through our number of full iterations until we reach 0, then we escape. This will break the recusive function. 
     if (fullInterations == 0) { 
      return 
     } 

     // Change the colors based on the array value 
     if (colors[currentArrayIndex] == 0) { 
      self.view.backgroundColor = UIColor.blackColor() 
     } 
     else if (colors[currentArrayIndex] == 1) { 
      self.view.backgroundColor = UIColor.whiteColor() 
     } 

     // Set our next index. Basically if the currentArrayIndex is at the end of our array, we reset it to 0 and subtract from the number of full iterations we've done. Otherwise we increment the array index 
     if (currentArrayIndex == colors.count - 1) { 
      currentArrayIndex = 0 
      fullInterations -= 1 
     } 
     else { 
      currentArrayIndex += 1 
     } 

     // Call our function recursively 
     performSelector(#selector(ViewController.cycleColors(_:)), withObject: [currentArrayIndex, fullInterations], afterDelay: 0.1) 
    } 

我們調用函數是這樣的:

override func viewDidLoad() { 
    super.viewDidLoad() 

    // We want to start at our first color and iterate through 5 times 
    cycleColors([0, 5]) 
}