Wednesday, 18 July 2012

CountDownTimer for iOS

.h File

@interface ViewController : UIViewController
{
    IBOutlet UILabel *myCounterLabel;
 
}

-(void)updateCounter:(NSTimer *)theTimer;
-(void)countdownTimer;
@property (nonatomic, retain) UILabel *myCounterLabel;


.m File


NSTimer *timer;
int hours, minutes, seconds;
int secondsLeft;




secondsLeft = 10;
 
    [self countdownTimer];




- (void)updateCounter:(NSTimer *)theTimer {
    if(secondsLeft > 0 ){
        secondsLeft -- ;
        hours = secondsLeft / 3600;
        minutes = (secondsLeft % 3600) / 60;
        seconds = (secondsLeft %3600) % 60;
        myCounterLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours,minutes,seconds];
        if (secondsLeft==0)
        {
            /*screen2 *np=[[screen2 alloc]init];
            [self.navigationController pushViewController:np animated:YES];*/
        }
    }
}


-(void)countdownTimer
{
 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
    [pool release];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [timer invalidate];
    timer = nil;
}


No comments: