Search code examples
iosobjective-canimationcore-animation

Point to Point Animation


http://postimg.org/image/8bwxdp4bj/7124c28f/ I want to make animation shown in above image .I am using this code .they became move to infinity and my view will not appear because they involved in for loop. I am newer in iOS . Please help.what i do I am stuck.Any help would be appreciated.

for (i=0; i<3; i++) {
        if (i==0) {
           first.backgroundColor=[UIColor blackColor];
           second.backgroundColor=[UIColor yellowColor];
            third.backgroundColor=[UIColor yellowColor];
            button.backgroundColor=[UIColor yellowColor];
            i=1;
        }
        if (i==1) {
            first.backgroundColor=[UIColor yellowColor];
            second.backgroundColor=[UIColor blackColor];
            third.backgroundColor=[UIColor yellowColor];
            button.backgroundColor=[UIColor yellowColor];
            i=2;
       }
        if (i==2) {
            first.backgroundColor=[UIColor yellowColor];
            second.backgroundColor=[UIColor yellowColor];
            third.backgroundColor=[UIColor blackColor];
            button.backgroundColor=[UIColor yellowColor];
            i=3;
        }
       if (i==3) {
            first.backgroundColor=[UIColor yellowColor];
            second.backgroundColor=[UIColor yellowColor];
           third.backgroundColor=[UIColor yellowColor];
            button.backgroundColor=[UIColor blackColor];
            i=0;
        }
    }

Solution

  • Firstly make a global variable which keeps track of which button's background is changed and also an array which stores all the buttons.

    @interface ClassName() {
        int index = 0;
        NSArray *buttons;
    }
    

    Now in the initialization method, do this

    [first setBackgroundColor:[UIColor yellowColor]];
    [second setBackgroundColor:[UIColor yellowColor]];
    [third setBackgroundColor:[UIColor yellowColor]];
    [button setBackgroundColor:[UIColor yellowColor]];
    buttons = @[first, second, third, button];
    [self performSelector:@selector(changeColor) withObject:nil afterDelay:1.0f];
    

    Now in your changeColor method, do like this

    - (void)changeColor {
    
        UIButton *btn = [buttons objectAtIndex:index];
        [btn setBackgroundColor:[UIColor blackColor]];
    
        UIButton *prevBtn = [buttons objectAtIndex:((index - 1) + 4) % 4];
        [prevBtn setBackgroundColor:[UIColor yellowColor]];
    
        index = ++ index % 4;
        [self performSelector:@selector(changeColor) withObject:nil afterDelay:1.0f];
    }