Dmitry Dmitry - 1 year ago 86
iOS Question

Blinking/Flashing UIView depending on bit in array

I am trying to blink iPhone screen (background color of UIView) depending on bit in array

(black - white its 1) or (white - black its 0).

But I can't figure out how to use loops and conditions in animation.

Not working code

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];
} else {
self.myBlock.backgroundColor = [UIColor whiteColor];
self.myBlock.backgroundColor = [UIColor blackColor];
i++; // how it can be increased ?

[UIView commitAnimations];

Any suggestions?

Answer Source

I apologize for the swift but converting to objective-c should be trivial. You can achieve your desired functionality using a recursive function like this.

We declare our array:

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

Our recursive function would look like this:

     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) {

        // 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)

We call the function like this:

override func viewDidLoad() {

    // We want to start at our first color and iterate through 5 times
    cycleColors([0, 5])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download