joec
joec

Reputation: 3543

Using NSTimer to create a countdown

I have a int value representing a countdown to an event (view being displayed). Currently, i do this:

- (void) buttonTapped:(id)sender {
    [self performSelector:@selector(displayView) afterDelay:countdownValue];
}

What I would like to do is the following...

When the button is tapped, change the tint colour of my navigation bar to red, yellow, green proportionally, until the countdown expires, then display the view.

So for example if my countdown is 3 seconds, one second for each colour, if it is 5 seconds, 1.666 for each colour.

Can I use an NSTimer to schedule this?

After the view is displayed the timer would need invalidating.

Thanks

Upvotes: 0

Views: 1463

Answers (1)

Max
Max

Reputation: 16709

float count_down = 5.0;
[NSTimer scheduledTimerWithTimeInterval: count_down*(1.0/3.0) target: self
                               selector: @selector(changeToRed:) userInfo: nil repeats: NO];
[NSTimer scheduledTimerWithTimeInterval: count_down*(2.0/3.0) target: self
                               selector: @selector(changeToGreen:) userInfo: nil repeats: NO];
[NSTimer scheduledTimerWithTimeInterval: count_down target: self
                               selector: @selector(changeToBlue:) userInfo: nil repeats: NO];

And callbacks (do whatever you want there):

-(void) changeToRed:(NSTimer*) t {
    NSLog(@"red");
}

-(void) changeToGreen:(NSTimer*) t {
    NSLog(@"green");
}

-(void) changeToBlue:(NSTimer*) t {
    NSLog(@"blue");
}

Upvotes: 3

Related Questions