2012-03-23 35 views
0

我正在为iPhone构建一个简单的健身/训练应用程序。用户可以从表格中选择一种类型的训练课程,将其带到包含秒表的视图控制器。该视图的标签由可变数组填充。以不同的时间间隔更改uilabel文本

我可以让秒表工作,并从数组中填充初始标签,但无法弄清楚如何让标签在设定的时间间隔内发生变化。这些时间间隔将不会是正常的,所以可能会在10分钟,然后是25,然后是45等。我一直试图通过If语句来执行此操作,例如定时器== 25。我确信这是一个基本的解决方案,但我是编程新手,无法解决问题。

定时器的代码如下:

- (void)updateTimer 
{ 
    NSDate *currentDate = [NSDate date]; 
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"HH:mm:ss.S"]; 
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 
    NSString *timeString=[dateFormatter stringFromDate:timerDate]; 
    timerLabel.text = timeString; 
} 

启动计时器:

- (IBAction)startTimerButton:(id)sender { 

    if (timer == nil) { 
     startDate = [NSDate date]; 

     // Create the stop watch timer that fires every 0.1s 

     timer = [NSTimer scheduledTimerWithTimeInterval:1.0/10 
               target:self 
               selector:@selector(updateTimer) 
               userInfo:nil 
               repeats:YES]; 

    } 

    else { 
     return; 
    } 
} 
+0

到目前为止运行此代码的结果是什么? – 2012-03-23 15:15:24

+0

没有生成错误和秒表正常工作。我无法弄清楚如何做If语句。我尝试了“if(timer == 5)[nextLable; setText ...]”,但是我得到一个错误'INT隐式转换为'NSTimer'不允许ARC' – pig70 2012-03-23 15:27:21

+0

Try(timer.timeInterval == 5)。 阅读NSTimer的类参考https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html – 2012-03-23 15:33:40

回答

0

我不太清楚你以后。如果您将时间间隔设置为10分钟/ 25分钟等而不是1.0/10,那么在您的时间触发代码中,您将知道计时器的时间间隔。

您可以始终使用timeInterval实例方法查询时间间隔。也许如下。

- (void)updateTimer:(NSTimer*)timer 
{ 
    if ([timer timeInterval] == 10 * 60) // 10 minutes have elapsed 
    { 
     // Do something for this timer. 
    } 
    else if ([timer timeInterval] == 20 * 60) // 20 minutes have elapsed 
    { 
    } 
} 

请注意,我已经添加了计时器作为参数传递给您的updateTimer功能。然后,您必须在scheduledTimerWithTimeInterval方法中使用@selector(update:)(在末尾带有冒号!)选择器。当您的回调选择器被调用时,它将传递给它的计时器。

或者,如果你有一个指针,你在你的“startTimerButton”你可以使用创建的计时器如下:

- (void)updateTimer:(NSTimer*)timer 
{ 
    if (timer == myTenMinuteTimer) // 10 minutes have elapsed 
    { 
     // Do something for this timer. 
    } 
    else if (timer == myTwentyMinuteTimer) // 20 minutes have elapsed 
    { 
    } 
} 

注意的是,在第二个原因你的指针比较两个对象和使用它,就像在第一次比较两个对象的方法的值一样,所以对象不一定是指向同一对象的指针,以便被评估为真。

希望这会有所帮助!

+0

谢谢你们。将与此一起去。 – pig70 2012-03-24 09:26:06

相关问题