开发者

Creating an iOS Timer

I am trying to create a "stop watch" type functionality. I have one label (to display the elapsed time) and two buttons (start and stop the timer). The start and stop buttons call the startTimer and stopT开发者_高级运维imer functions respectively. Every second the timer fires and calls the increaseTimerCount function. I also have an ivar timerCount which holds on to the elapsed time in seconds.

- (void)increaseTimerCount
{
    timerCountLabel.text = [NSString stringWithFormat:@"%d", timerCount++];
}

- (IBAction)startTimer
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(increaseTimerCount) userInfo:nil repeats:YES];

}

- (IBAction)stopTimer
{
    [timer invalidate];
    [timer release];
}

The problem is that there seems to be a delay when the start button is pressed (which I am assuming is due to reinitializing the timer each time startTimer is called). Is there any way to just pause and resume the timer without invalidating it and recreating it? or a better/alternate way of doing this?

Thanks.


A bit dated but if someone is still interested...

don't "stop" the timer, but stop incrementing during pause, e.g.

- (void)increaseTimerCount
{
   if (!self.paused){
      timerCount++
   }

   timerCountLabel.text = [NSString stringWithFormat:@"%d", timerCount];
}


You can't pause the timer without using invalidate. What you can do is add

[timer fire];

after you create the timer in startTimer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜