簡體   English   中英

在 Objective-c 中實現倒數計時器?

[英]Implementing a Countdown Timer in Objective-c?

我是 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];

請任何人指導我如何在幾分鍾和幾秒鍾內做到這一點。

你可以這樣做(啟用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];
    }
}

我知道這是個老問題,但我想分享我實現這一目標的方法。 我們有方法 (timeIntervalSinceDate:) 來計算間隔並有固定的秒數倒計時。 在我的情況下是 300 秒。

2015 年 7 月更新

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

工作 github swift 示例項目

目標-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

在 .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;
}

將上面的Label Outlet 與View 中的Label 綁定。

它與我一起正常工作

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

您可以使用NSTimer來實現這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM