在Objective-c中实现倒数计时器?

时间:2012-05-19 07:17:32

标签: iphone objective-c ios nstimer

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

  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中,我通过计时器调用它。

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

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

5 个答案:

答案 0 :(得分:54)

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

@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];
    }
}

答案 1 :(得分:18)

我知道这是一个老问题,但我想分享我的方式来实现这一目标。我们有方法(timeIntervalSinceDate :)来计算间隔并具有固定的倒数秒数。在我的情况下300秒。

2015年7月更新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 timeString = dateFormatter.stringFromDate(timerDate);
    self.timerLabel?.text = timeString;
}

Working github swift sample project

<强>目标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
    NSString *timeString = [dateFormatter stringFromDate:timerDate];
    self.stopWatch.text = timeString;
}

- (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];
}

<强>更新

每次通过updateTimer创建NSDateFormatter都非常昂贵。最好在循环外创建NSDateFormatter并重用它。致谢:@siburb

答案 2 :(得分:3)

在.h文件中

 IBOutlet UILabel* lblTimer;
 NSTimer* gameTimer;

在.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 = [NSString stringWithFormat:@"%02d:%02d",timeCount/60, timeCount % 60];
   self.title = lblTimer.text;
}

使用View中的Label绑定上面的Label Outlet。

它与我正常工作

答案 3 :(得分:1)

Objective-C中的简单代码,

in .h file create objects for Timer and totalSeconds

 NSTimer *timer;
 int totalSeconds;

.m file
//you can call this method where you want 
[self startTimer];

-(void)startOtpTimer {
     totalSeconds = 120;//your time 
     timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self 
     selector:@selector(updateCountDownTime) userInfo:nil repeats:YES];
 }

-(void)updateCountDownTime {
    [self populateLabelwithTime:totalSeconds];
        if( totalSeconds != 0) {
            totalSeconds -= 1;
        } else {
              [timer invalidate];//stop timer
              self.timeLabel.text = @"";//after reach 0 you can set empty string
         }
}

- (void)populateLabelwithTime:(int)seconds {
    self.timeLabel.text = [NSString stringWithFormat:@"%02d", totalSeconds];
}

答案 4 :(得分:0)

您可以使用NSTimer来实现此目标。