我已经实现了一些代码,允许用户使用UIDatePicker设置倒计时的时间限制,然后用户按下"开始"按钮,倒计时就会打印到UILabel中。
我正在想办法停止计时器。这是我迄今为止启动计时器的代码:
@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
}
有什么想法吗?
您需要保留对NSTimer
的引用作为ivar:
@implementation P11DetailController
{
NSTimer *myTimer;
}
然后:
myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self
selector:@selector(updateCountDown) userInfo:nil repeats:YES];
然后简单调用:
[myTimer invalidate];
将停止计时器。
这些都在文档中,您应该首先查阅这些文档。