根据数组中的位闪烁/闪烁UIView

时间:2016-08-17 15:59:35

标签: ios objective-c

我试图使iPhone屏幕(UIView的背景颜色)闪烁,具体取决于数组[0,1,1,0,0,1,1,0]中的位(黑色 - 白色1)或(白色 - 黑色0)。

但我无法弄清楚如何在动画中使用循环和条件。

无效代码

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]; 

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我为迅速而道歉但转换为目标-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])
}