我创建了一个显示在标签上的倒数计时器,现在我想添加一个功能,即用户按下按钮的eberytime它将向倒数计时器添加30秒。 我试图自己做,但我没有成功(我有一个错误,一次它停止我的计时器)我怎么能这样做? 这是我的代码:
-(IBAction)start:(id)sender
{
timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
}
-(void)updateTimer:(NSTimer *)timer
{
currentTime -= 10 ;
[self populateLabelwithTime:currentTime];
if(currentTime <=0)
{
[timer invalidate];
//some code when countdown reach to 00:00:00
}
}
- (void)populateLabelwithTime:(int)milliseconds {
seconds = milliseconds/1000;
minutes = seconds / 60;
seconds -= minutes * 60;
NSString * countdownText = [NSString stringWithFormat:@"%@%02d:%02d:%02d", (milliseconds<0?@"-":@""), minutes, seconds,milliseconds%1000];
countdownLabel.text = countdownText;
}
-(IBAction)addTime:(id)sender
{
timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(addToCurrent:) userInfo:nil repeats:YES];
}
-(void) addToCurrent:(NSTimer *)timerb;
{
seconds +=10;
[self populateLabelWithTime:seconds];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
currentTime = 2700;
}
谢谢!
答案 0 :(得分:0)
每按一次按钮都无需重新创建计时器。另外,当你试图向计时器添加30秒时,我觉得你不小心修改了秒而不是当前时间。
-(IBAction)addTime:(id)sender
{
currentTime += 30000;
[self populateLabelWithTime:currentTime];
}