iPhone向应用程序添加计时器
我将如何在我的应用程序中添加一个简单的2分钟计时器,几乎与时钟应用程序完全相同?我只希望用户单击开始,让计时器开始显示计时器从2:00开始倒计时,并在0:00时发出嘟嘟声。这可能正是您想要的。您可以使用。我创建了一些生成计时器的基本代码 当用户选择启动计时器时,将调用此方法:iPhone向应用程序添加计时器,iphone,objective-c,Iphone,Objective C,我将如何在我的应用程序中添加一个简单的2分钟计时器,几乎与时钟应用程序完全相同?我只希望用户单击开始,让计时器开始显示计时器从2:00开始倒计时,并在0:00时发出嘟嘟声。这可能正是您想要的。您可以使用。我创建了一些生成计时器的基本代码 当用户选择启动计时器时,将调用此方法: -(void)startTimer{ timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(countdown) userInfo
-(void)startTimer{
timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(countdown) userInfo:nil repeats:YES];//Timer with interval of one second
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
触发计时器时将调用此方法:
-(void)countdown{
NSLog(@"Countdown : %d:%d",minutesValue,secondsValue);//Use this value to display on your UI Screen
[self countdownSeconds];//Decrement the time by one second
}
将调用此方法以将时间减少一分钟:
-(void)countdownMinutes{
if(minutesValue == 0)
[self stopTimer];
else
--minutesValue;
}
将调用此方法以将时间减少1秒:
-(void)countdownSeconds{
if(secondsValue == 0 )
{
[self countdownMinutes];
secondsValue = 59;
}
else
{
--secondsValue;
}
}
当计时器达到零时调用此方法:
-(void)stopTimer{
[timer invalidate]; //Stops the Timer and removes from runloop
NSLog(@"Countdown completed"); // Here you can add your beep code to notify
}
“timer”、“minutesValue”和“secondsValue”是实例变量。我昨天写了这篇文章,你可能会发现它很有用。它是一种从NSTimeInterval中提取小时、分钟和秒的方法(这是一个双精度结构,表示两次之间的秒数——在本例中,
NSDate self.expires
和[NSDate date]
,即现在)。这是在自定义表格单元格视图中发生的。最后,我们在一个小小的秒表显示屏上更新了三个UILabel
-(void)updateTime
{
NSDate *now = [NSDate date];
NSTimeInterval interval = [self.expires timeIntervalSinceDate:now];
NSInteger theHours = floor(interval / 3600);
interval = interval - (theHours * 3600);
NSInteger theMinutes = floor(interval / 60);
interval = interval - (theMinutes * 60);
NSInteger theSeconds = floor(interval);
NSLog(@"%d hours, %d minutes, %d seconds", theHours, theMinutes, theSeconds);
self.hours.text = [NSString stringWithFormat:@"%02d", theHours];
self.minutes.text = [NSString stringWithFormat:@"%02d", theMinutes];
self.seconds.text = [NSString stringWithFormat:@"%02d", theSeconds];
}
然后在其他地方我设置了一个计时器,每秒调用一次这个方法。计时器不能保证在精确的特定时间运行,这就是为什么您不能只倒计时一些静态变量,或者随着时间的推移,您会面临累积错误的风险。事实上,你每次打电话都要做新的时间计算
请确保保留指向计时器的指针,并在viewcontroller消失时使其无效