Implémentation d'un count à rebours dans Objective-c?

Je suis nouveau à la programmation iOS. Je travaille sur des mots correspondant à un jeu. Dans ce jeu, j'ai besoin de mettre en place un countur de time qui montre les minutes et les secondes. Je veux quand mon jeu est commencé mon chronomètre pour commencer avec 3 minutes. Maintenant, je veux diminuer cette timer dans le sens inverse avec quelques secondes. mon code fonctionne juste pour quelques secondes … il y a mon code:

secondsLeft--; int seconds = (secondsLeft %3600) % 60; Timerlbl.text = [NSSsortingng ssortingngWithFormat:@"%02d",seconds]; if (seconds==0) { UIAlertView *pAlert = [[UIAlertView alloc]initWithTitle:@"Sorry!!" message:@"TimeOver" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel",nil]; [pAlert show]; [pAlert release]; } } 

Dans Viewdidload je l'appelle par le biais de la timer ..

  countDown=[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(TimeOver) userInfo:nil repeats:YES]; 

plaide tout un guide moi comment puis-je le faire dans les deux minutes et secondes.

Vous pouvez le faire comme ceci (ARC activé): –

 @interface ViewController() { UILabel *progress; NSTimer *timer; int currMinute; int currSeconds; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; progress=[[UILabel alloc] initWithFrame:CGRectMake(80, 15, 100, 50)]; progress.textColor=[UIColor redColor]; [progress setText:@"Time : 3:00"]; progress.backgroundColor=[UIColor clearColor]; [self.view addSubview:progress]; currMinute=3; currSeconds=00; // Do any additional setup after loading the view, typically from a nib. } -(void)start { timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES]; } -(void)timerFired { if((currMinute>0 || currSeconds>=0) && currMinute>=0) { if(currSeconds==0) { currMinute-=1; currSeconds=59; } else if(currSeconds>0) { currSeconds-=1; } if(currMinute>-1) [progress setText:[NSSsortingng ssortingngWithFormat:@"%@%d%@%02d",@"Time : ",currMinute,@":",currSeconds]]; } else { [timer invalidate]; } } 

Je sais que c'est une vieille question, mais je veux partager mon path pour y parvenir. Nous avons la méthode (timeIntervalSinceDate 🙂 pour calculer l'intervalle et avoir une quantité fixe de secondes à décountr. Dans mon cas 300 s.

MISE À JOUR JUILLET 2015 SWIFT

 @IBAction func startTimer(sender: UIButton) { sender.selected = !sender.selected; //if selected fire timer, otherwise stop if (sender.selected) { self.timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateTimer"), userInfo: nil, repeats: true); self.startDate = NSDate(); } else { self.stopTimer(); } } func stopTimer() { self.timer.invalidate(); } func updateTimer() { // Create date from the elapsed time var currentDate:NSDate = NSDate(); var timeInterval:NSTimeInterval = currentDate.timeIntervalSinceDate(self.startDate!); //300 seconds count down var timeIntervalCountDown = 300 - timeInterval; var timerDate:NSDate = NSDate(timeIntervalSince1970: timeIntervalCountDown); // Create a date formatter var dateFormatter = NSDateFormatter(); dateFormatter.dateFormat = "mm:ss"; dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0); // Format the elapsed time and set it to the label var timeSsortingng = dateFormatter.ssortingngFromDate(timerDate); self.timerLabel?.text = timeSsortingng; } 

Travailler github swift exemple de projet

Objectif c

 - (void)updateTimer { // Create date from the elapsed time NSDate *currentDate = [NSDate date]; NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:self.startDate]; NSLog(@"time interval %f",timeInterval); //300 seconds count down NSTimeInterval timeIntervalCountDown = 300 - timeInterval; NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeIntervalCountDown]; // Create a date formatter NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"mm:ss"]; [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; // Format the elapsed time and set it to the label NSSsortingng *timeSsortingng = [dateFormatter ssortingngFromDate:timerDate]; self.stopWatch.text = timeSsortingng; } - (void)stopTimer { [self.stopWatchTimer invalidate]; self.stopWatchTimer = nil; [self updateTimer]; } - (void)startTimer { if (self.stopWatchTimer) { [self.stopWatchTimer invalidate]; self.stopWatchTimer = nil; } self.startDate = [NSDate date]; // Create the stop watch timer that fires every 100 ms self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES]; } 

METTRE À JOUR:

Il est extrêmement coûteux de créer un NSDateFormatter chaque fois que vous passez par updateTimer. Il vaut mieux créer le NSDateFormatter en dehors de la boucle et le réutiliser. Crédits: @siburb

Dans le file .h

  IBOutlet UILabel* lblTimer; NSTimer* gameTimer; 

Dans le file .m

 -(void)viewDidLoad { [super viewDidLoad]; [self createTimer]; } - (void)createTimer { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; gameTimer = [[NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES] retain]; [[NSRunLoop currentRunLoop] addTimer:gameTimer forMode:NSDefaultRunLoopMode]; timeCount = 20; [runLoop run]; [pool release]; } - (void)timerFired:(NSTimer *)timer { if(timeCount == 0) { [self timerExpired]; } else { timeCount--; if(timeCount == 0) { [timer invalidate]; [self timerExpired]; } } lblTimer.text = [NSSsortingng ssortingngWithFormat:@"%02d:%02d",timeCount/60, timeCount % 60]; self.title = lblTimer.text; } 

Liez la sortie d'label ci-dessus avec Label dans la vue.

Cela fonctionne correctement avec Moi

Vous pouvez utiliser NSTimer pour y parvenir.