【问题标题】:Countdown timer between time interval iPhone时间间隔 iPhone 之间的倒数计时器
【发布时间】:2011-08-24 12:46:21
【问题描述】:

我需要 iPhone 识别当前时间(我可以用 NSDate 很好地做到这一点)并让它倒计时到下一个时间间隔,比如半小时每半小时。示例:如果当前时间是 2:12:30 并且间隔是每半小时,我希望倒计时从 17:30 开始(还剩 17 分 30 秒)并转到 0。

欢迎代码,也欢迎一般的程序设计思想。这是我用于开始倒计时并获取当前时间的代码:

-(void)updateCounter:(NSTimer *)theTimer {
        if(secondsLeft > 0 ){
            secondsLeft -- ;
            minutes = (secondsLeft % 3600) / 60;
            seconds = (secondsLeft % 3600) % 60;
            waitingTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
        }
        else{
            secondsLeft = 10;
        }
    }

    -(void)countdownTimer{
        //secondsLeft = minutes = seconds = 0;
        if([timer isValid])
        {
            [timer release];
        }
       // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
        //[pool release];
    }
    -(NSDate *)getCurrentTime
    {
        NSDate *now = [NSDate date];

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"mm:ss";

        [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
        NSLog(@"The Current Time is %@",[dateFormatter stringFromDate:now]);
        //[dateFormatter release];
        NSString *currentTime = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:now]];
        currentTimeLabel.text = currentTime;
        return now;
    }

【问题讨论】:

  • 我想过用 TimeIntervalSinceDate 从另一个中减去一个时间,但这需要添加所有潜在的间隔
  • 更具体地说,我只想规定所需的时间间隔,每 10 分钟或每小时一次,然后倒计时。
  • 你知道时间间隔对吗?那么你使用 TimeIntervalSinceDate 吗?
  • 只需放置一个标签,使用 NSTimer 通过将计时器间隔设置为 1 每秒更新标签值。
  • 如果有人在 2:15:30 按下按钮,而另一个使用该应用程序的人在 2:17:30 按下按钮,我希望两个计时器都倒计时到 2:30:00。更新倒计时不是问题,它让手机知道如果间隔是每 30 次,则分别只倒计时 14:30 和 12:30。

标签: iphone nsdate nstimer


【解决方案1】:
NSDate *now = [NSDate date];
int interval = 30*60; // half hour
long int nowSeconds = (long int) [now timeIntervalSince1970];
int secondsLeft = interval - (nowSeconds % interval); 
NSDate *nextIntervalDate =  [NSDate 
    dateWithTimeIntervalSince1970:nowSeconds+secondsLeft];

NSLog(@"Now is %@", now);
NSLog(@"The next interval point in time is %@", nextIntervalDate);
NSLog(@"That's another %d seconds (or %02d:%02d)", 
    secondsLeft, secondsLeft/60, secondsLeft%60);

【讨论】:

  • 哇,Mundi 太牛了。谢谢!
  • 我把它放在我的 viewDidLoad 方法中,每次 viewLoads 时,它都会将倒计时增量增加一秒。如果它加载一次,它会正确倒计时一秒。两次,它每秒倒计时 2 秒...有什么想法吗?
  • 也许您必须检查您的旧 NSTimer 是否仍在运行。如果是,请取消它。否则,您有 2 个或更多计时器正在运行,它们都会调整倒计时字段...
  • 是视图会消失,而不是视图没有卸载。现在效果很好。谢谢!
猜你喜欢
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多