2015-04-05 74 views
1

我已经实现了一些代码,允许用户设置使用UIDatePicker的倒计时时间限制,然后用户按下“开始”按钮并将倒计时打印到UILabel中。使用UIButton停止NSTimer

我想找到一种方法来停止计时器。这里是我到目前为止的代码,启动定时器:

@implementation P11DetailController 
int afterRemainder; 
int iRemainder; 
NSTimeInterval countDownInterval; 

- (void)updateCountDown{ 
afterRemainder --; 

int hours = (int)(afterRemainder)/(60*60); 
int mins = (int)(((int)afterRemainder/60) - (hours * 60)); 
int secs = (int)(((int)afterRemainder - (60 * mins) - (60*hours*60))); 

NSString *displayText = [[NSString alloc] initWithFormat:@"%02u : %02u : 
%02u", hours, mins, secs]; 

self.displayLabel.text = displayText; 
} 

那么当用户用户按下“开始”:

- (IBAction)startButton:(id)sender { 
countDownInterval = (NSTimeInterval)_countdownTimer.countDownDuration; 
iRemainder = countDownInterval; 
afterRemainder = countDownInterval - iRemainder%60; 
[NSTimer scheduledTimerWithTimeInterval:1 target:self 
selector:@selector(updateCountDown) userInfo:nil repeats:YES]; 

}

最后,用户按下时“停止“:

- (IBAction)stopButton:(id)sender { 
//not sure what to add here 

} 

有什么想法吗?

回答

2

你需要一个参考保持到NSTimer为伊娃:

@implementation P11DetailController 
{ 
NSTimer *myTimer; 
} 

则:

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

然后简单地调用:

[myTimer invalidate];

威尔停止计时器。

这一切都在documentation你应该先咨询。

+0

非常好。谢谢。此外,当我的计时器达到零时,它不会停止,它会进入类似00:00:429474924928的状态并继续计数。当我的当前代码碰到00:00:00时,有没有办法停止计时器? – willfo 2015-04-05 16:53:01

+0

我已经设法实现这个使用if语句来检查值是否为0并使计时器无效。 – willfo 2015-04-05 17:00:20

+0

好。做得好。 – 2015-04-05 17:00:59