我开发秒表应用程序。在我的应用程序中,有两个UIButtonStartBtn
和StopBtn
,我也使用NSTimer
。
现在,我想NSTimer
在用户单击时开始,StartBtn
并且在您单击时也停止StopBtn
。
我知道该方法NSTimer
已停止,[MyTimerName invalidate];
但我不知道如何重新开始NSTimer
?
该NSTimer
班是一个有点尴尬的使用; 而不是将创建/破坏与开始/停止分离开来,而是将它们全部组合在一起。换句话说,计时器在创建后立即启动,在销毁后立即停止。
因此,您需要使用存在的的NSTimer
对象作为标志,以表明它是否运行; 像这样的东西:
// Private Methods
@interface MyClass ()
{
NSTimer *_timer;
}
- (void)_timerFired:(NSTimer *)timer;
@end
@implementation MyClass
- (IBAction)startTimer:(id)sender {
if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(_timerFired:)
userInfo:nil
repeats:YES];
}
}
- (IBAction)stopTimer:(id)sender {
if ([_timer isValid]) {
[_timer invalidate];
}
_timer = nil;
}
- (void)_timerFired:(NSTimer *)timer {
NSLog(@"ping");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句