c中实现倒数计时器

c中实现倒数计时器

本文介绍了在Objective-c中实现倒数计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iOS编程新手。我正在研究匹配游戏的文字。在这个游戏中,我需要实现时间计数器,显示分钟和秒。我希望当我的游戏开始时我的计时器以3分钟开始。现在我想用秒来反向减少这个计时器。我的代码工作了几秒钟......我的代码是:

I am new to iOS programming. I am working on words matching game. In this game I need to implement time counter which shows minutes and seconds. I want when my game is started my timer to start with 3 minutes. Now I want to decrease this timer in reverse direction with seconds. my code just work for seconds..here is my code:

  secondsLeft--;

  int seconds = (secondsLeft %3600) % 60;

  Timerlbl.text = [NSString stringWithFormat:@"%02d",seconds];


  if (seconds==0)

{


 UIAlertView *pAlert = [[UIAlertView alloc]initWithTitle:@"Sorry!!"
 message:@"TimeOver"        delegate:self    cancelButtonTitle:@"OK"
 otherButtonTitles:@"Cancel",nil];

 [pAlert show];

[pAlert release];

 }

 }

在Viewdidload中通过计时器调用..

In Viewdidload i call it through timer..

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

请任何人指导我如何在分钟和秒钟内完成。

pleas any one guide me how can i do it in both minutes and seconds.

推荐答案

你可以这样做(启用ARC): -

You can do it like this(ARC Enabled):-

@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:[NSString stringWithFormat:@"%@%d%@%02d",@"Time : ",currMinute,@":",currSeconds]];
}
    else
    {
        [timer invalidate];
    }
}

这篇关于在Objective-c中实现倒数计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:47