【发布时间】:2019-02-10 21:14:05
【问题描述】:
如何以与时钟应用几乎完全相同的方式在我的应用中添加一个简单的 2 分钟计时器?我只希望用户单击开始并让计时器开始显示计时器从 2:00 开始倒计时并在到达 0:00 时发出哔哔声。
【问题讨论】:
标签: iphone objective-c
如何以与时钟应用几乎完全相同的方式在我的应用中添加一个简单的 2 分钟计时器?我只希望用户单击开始并让计时器开始显示计时器从 2:00 开始倒计时并在到达 0:00 时发出哔哔声。
【问题讨论】:
标签: iphone objective-c
我已经创建了一些用于生成计时器的基本代码。
当用户选择启动计时器时,该方法将被调用:
-(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;
}
将调用此方法将时间减一秒:
-(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];
}
然后我在其他地方设置了一个计时器来每秒调用一次此方法。定时器不能保证在其确切的特定时间运行,这就是为什么你不能只对一些静态变量进行倒计时,或者你冒着随着时间的推移累积错误的风险。相反,您实际上必须在每次通话时进行新的时间数学运算。
确保您保留一个指向计时器的指针,并在您的视图控制器消失时使其无效!
【讨论】:
这可能正是你想要的Orientation aware clock tutorial
【讨论】:
你可以使用NSTimer。
【讨论】: