0

到现在为止,我一直在网上搜索几天。我确实找到了一些有用的信息,但只是想让事情变得完美。

我正在尝试编写一个只使用秒的倒计时应用程序,我当前的代码有点太复杂了,可能不在主要道路上。想找一个能整的人。

- (void)updateTimer{

NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"s"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];

// where the part change time string back to int
NSString *changeToInt = timeString;
int stringInt = [changeToInt integerValue];

// loop for count down numbers
if ((buttValue - stringInt) > 0) {
    leftTime = buttValue - stringInt;
    [self updateValue];
} else {
    leftTime = 0;
    [self updateValue];
}

}

代码有2个问题,1)我是否必须通过所有日期格式才能获得整数?2)在循环中我使用了两个变量,我希望取出一个并使用类似的东西——

4

3 回答 3

0
 -(void)initialiseTimer
{
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeElapsed) userInfo:nil repeats:YES];
    startDate = [[NSDate date] retain];

}
-(void)timeElapsed
{

    NSLog(@"Seconds elapsed since start date %d", abs([startDate timeIntervalSinceNow]));

}

你可以操纵它来制作一个倒计时风格的应用程序。

于 2012-03-26T09:18:05.433 回答
0

我不明白你到底需要什么,但我认为你只想得到从现在到已知日期的秒数。timeIntervalSinceNow 方法将为您提供一个 NSInteger 值,该值表示从接收者日期到现在的秒数,如果接收者早于现在,它将是一个负值(否则它将是正值)。

所以,更明确地说:

- (void)updateTimer
{
    leftTime = MAX(0, -[startDate timeIntervalSinceNow]); //if less than 0 will be forced to 0 -> date reached
    [self updateValue];
}

正如我所说,我不确定这是你想要的。如果不是,我很抱歉。祝你好运!

于 2012-03-26T09:11:04.353 回答
0

使用此代码!

-(IBAction)startAndStop:(id)sender
{
    startDate = [[NSDate date]retain];
    if([btnStopWatch.titleLabel.text isEqualToString:@"Start"])
    {
        stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/100.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
        [btnStopWatch setTitle:@"Stop" forState:UIControlStateNormal];
    }
    else if([btnStopWatch.titleLabel.text isEqualToString:@"Stop"])
    {
        [stopWatchTimer invalidate];
        [btnStopWatch setTitle:@"Start" forState:UIControlStateNormal];
    }
}
- (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"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    timeString=[dateFormatter stringFromDate:timerDate];
    stopWatchLabel.text = timeString;
    NSLog(@"Seconds elapsed since start date %d", abs([startDate timeIntervalSinceNow]));

}
于 2012-03-26T10:14:35.720 回答