-1

我正在使用 Xcode 4 作为单视图应用程序进行秒表。不过我有一个问题。当毫秒计数时,它们会无限循环。我希望它们达到 9,然后从 0 重新开始。我还希望秒数达到 59,然后回到 0。这是我的 viewcontroller.m 文件中的代码:

- (IBAction)start{

    myTicker = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];  


    myTicker2 = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(showActivity1) userInfo:nil repeats:YES];

    myTicker3 = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(showActivity2) userInfo:nil repeats:YES];


}
- (IBAction)stop{

    [myTicker invalidate];
    [myTicker2 invalidate];
    [myTicker3 invalidate];
}
- (IBAction)reset{

    time.text = @"00";
    time1.text = @"00";
    time2.text = @"00";
}


- (void)showActivity{

    int currentTime = [time.text intValue];
    int newTime = currentTime + 1;
    time.text = [NSString stringWithFormat:@"%d", newTime];

    }



- (void)showActivity1{


    int currentTime1 = [time1.text intValue];
    int newTime1 = currentTime1 + 1;
    time1.text = [NSString stringWithFormat:@"%d", newTime1];


}


- (void)showActivity2{


    int currentTime2 = [time2.text intValue];
    int newTime2 = currentTime2 = 1;
    time2.text = [NSString stringWithFormat:@"%d", newTime2];



}

这是我在 .h 文件中的代码。

    IBOutlet UILabel *time;
    IBOutlet UILabel *time1;
    IBOutlet UILabel *time2;

    NSTimer *myTicker;
    NSTimer *myTicker2;
    NSTimer *myTicker3;
}

- (IBAction)start;
- (IBAction)stop;
- (IBAction)reset;


- (void)showActivity;
- (void)showActivity1;
- (void)showActivity2;

@end

任何有关如何做到这一点的答案将不胜感激。谢谢。

4

1 回答 1

0

在您的情况下,我将只使用 1 个计时器(一个计数毫秒)和 4 个 int vars(小时、分钟、秒和毫秒)。然后在计时器滴答声中,您只需测试

if (milliseconds > 999)
{
    seconds++;
    milliseconds = 0;
}
if (seconds > 59)
{
    minutes++;
    seconds = 0;
}
if (minutes > 59)
{
    hours++;
    minutes = 0;
}

因此,通过这样做,您将拥有一个管理所有变量的计时器。我写了这段代码,所以它可能有拼写错误。

于 2012-07-08T14:07:58.167 回答