简体   繁体   English

如何在iOS中从零开始计时

[英]How to start a timer from zero in iOS

I have a button on which i have placed a UITapGestureRecognizer. 我有一个放置了UITapGestureRecognizer的按钮。 When i tap on that button, i call a method that starts the time. 当我点击那个按钮时,我调用一个开始时间的方法。 My question is, i am able to get the timer string on a label. 我的问题是,我能够在标签上获取计时器字符串。 But the timer starts from current date-time, and i want to start the timer always from zero(like a countdown timer). 但是计时器从当前日期时间开始,我想始终从零开始计时(例如倒数计时器)。 Here below is my code for timer. 以下是我的计时器代码。

-(IBAction)micPressed{
if (gestureRecognizer.state==UIGestureRecognizerStateBegan) {
    gestureRecognizer.view.alpha=0.2f;

    [label setHidden:NO];

    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1f
                                                  target:self
                                                selector:@selector(_timerFired:)
                                                userInfo:nil
                                                 repeats:YES];
    }
}
else{
    [label setHidden:YES];

    gestureRecognizer.view.alpha=10.2f;
    if ([_timer isValid]) {
        [_timer invalidate];
    }
    _timer = nil;
}

}

- (void)_timerFired:(NSTimer *)timer {

 NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setDateFormat:@"mm:ss:SSS"];

NSString *dateInStringFormated=[dateformatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
NSLog(@"%@",dateInStringFormated);
[label setText:dateInStringFormated];
}

Please can anyone suggest me the solution. 请谁能给我建议解决方案。 Any help is appreciated. 任何帮助表示赞赏。

The problem is you are starting your timer from current time itself. 问题是您正在从当前时间本身启动计时器。 To make a like countdown timer. 使一个倒数计时器。 You need to do the following: 您需要执行以下操作:

  1. Take an int named Counter and intialize it from 0 以一个名为Counterint并将其从0初始化
  2. Fire your NSTimer and at that time increase the counter 触发您的NSTimer并在那时增加计数器
  3. Display the counter value in the UILabel text. UILabel文本中显示计数器值。
  4. Once your NSTimer stops, again make it to 0 . NSTimer停止后,再次将其设置为0

That's it! 而已! This is how you can achieve the desired result. 这样可以达到预期的效果。

Code: 码:

int counter = 0;

- (void)_timerFired:(NSTimer *)timer {
    counter++;
}

Once NSTimer is invalidate again make it to counter = 0 一旦NSTimer再次失效,使其counter = 0

Your code should be like, 您的代码应该像

 NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setDateFormat:@"mm:ss:SSS"];

NSString *dateInStringFormated=[dateformatter stringFromDate:[dateformatter dateFromString:@"00:00:000"]];
NSLog(@"test : %@",dateInStringFormated);

I have just chage [NSDate dateWithTimeIntervalSinceNow:0] with [dateformatter dateFromString:@"00:00:000"] . 我只是用[dateformatter dateFromString:@"00:00:000"] [NSDate dateWithTimeIntervalSinceNow:0] [dateformatter dateFromString:@"00:00:000"]

It will start with zero always. 它将始终从零开始。

Update : 更新:

I think you want something like timer that update minutes,seconds and milliseconds as i understand your question now. 我想您希望像计时器这样的东西可以更新分钟,秒和毫秒,因为我现在了解您的问题。 You can achieve it something like, 您可以实现以下目标,

Schedule timer like, 安排计时器,例如

   NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];

Now your updateTimer should be like, 现在您的updateTimer应该像

 -(void)updateTimer{

 static double counter = 0;

 static int counter2 = 0;


int seconds = (int)counter % 60;
int minutes = ((int)counter / 60) % 60;


NSLog(@"%02d:%02d:%03d",minutes,seconds,counter2); // This should be your labels text that updating continuously




counter = counter + 0.01;
counter2++;

if (counter2 == 100) {
    counter2 = 0;
}
}

Hope this will help :) 希望这会有所帮助:)

Remember the time when you have started the timer: 记住启动计时器的时间:

_startDate = [NSDate date];
_Timer = ...

Then use the time interval since the start date in your _timerFired method: 然后在_timerFired方法中使用自开始日期起的时间间隔:

NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
NSString *dateInStringFormatted = [formatter stringFromTimeInterval:[[NSDate date] timeIntervalSinceDate:_startDate]];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM