我在我的程序中使用 NSTimer 来播放视频,NSTimer 连续运行以在函数中运行我如何暂停和恢复 NSTimer 的操作,我的操作是-
-(void)handleTap
{
if(pause==YES)
{
//resume ;
}
else
{
//pause;
}
}
NSTimer 中没有暂停和恢复功能。你可以像下面提到的代码那样做。
- (void)startTimer {
m_pTimerObject = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(fireTimer:) userInfo:nil repeats:YES];
}
- (void)fireTimer:(NSTimer *)inTimer {
// Timer is fired.
}
- (void)resumeTimer {
if(m_pTimerObject) {
[m_pTimerObject invalidate];
m_pTimerObject = nil;
}
m_pTimerObject = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(fireTimer:) userInfo:nil repeats:YES];
}
- (void)pauseTimer {
[m_pTimerObject invalidate];
m_pTimerObject = nil;
}
我希望这些代码片段对您有所帮助。
你不能暂停计时器。
您可以:
nstimer 中没有暂停和恢复的特定方法。如果您想停止计时器,则需要使计时器无效
在执行操作时,您可以使用[timer invalidate];
,当您想恢复时,您只需重新启动计时器
您不能暂停计时器。您可以保存计时器的 fireDate 以及当前日期。在此之后,您使计时器无效。当需要恢复计时器时,您创建一个新的计时器对象并将触发日期设置为旧触发日期加上用户在菜单中的时间(oldTime + currentTime)。
- (IBAction)pauseResumeTimer:(id)sender {
if (timerRunning == NO) {
timerRunning = YES;
[pauseTimerBtn setTitle:@"Resume" forState:UIControlStateNormal];
NSString *stringVal = [NSString stringWithFormat:@"%@",timeTxt.text];
stringVal = [stringVal stringByReplacingOccurrencesOfString:@":" withString:@"."];
float tempFloatVal = [stringVal floatValue];
int minuteValue = floorf(tempFloatVal);
float tempSecVal = [stringVal floatValue] - floorf(tempFloatVal);
int secondVal = tempSecVal*100;
minuteValue = minuteValue*60;
oldTimeValue = minuteValue + secondVal;
[timer invalidate];
timer = nil;
}
else
{
timerRunning = NO;
[pauseTimerBtn setTitle:@"Pause" forState:UIControlStateNormal];
startDate = [NSDate date];
timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
}
}
- (void)runTimer:(NSTimer *)timer {
NSInteger secondsAtStart = (NSInteger)[[NSDate date] timeIntervalSinceDate:startDate];
secondsAtStart = secondsAtStart + oldTimeValue;
NSInteger seconds = secondsAtStart % 60;
NSInteger minutes = (secondsAtStart / 60) % 60;
NSInteger hours = secondsAtStart / (60 * 60);
NSString *result = nil;
result = [NSString stringWithFormat:@"%02ld:%02ld",(long)minutes,(long)seconds];
timeTxt.text = result;
}
我编写了一个可以处理暂停和取消暂停计时器的控制器类。你可以在这里找到它:https ://github.com/LianaChu/LCPausableTimer
它的工作原理与 BornCoder 的答案非常相似。如果您发现自己需要在项目中经常暂停和取消暂停计时器,则此控制器类会很有用。
如果您使用它,我将不胜感激任何评论或反馈,例如您如何使用它、您希望看到哪些更改或您希望我添加的任何功能。请不要犹豫,在这里回复您的评论,或在 github 页面上的问题选项卡上发布。
请看下面的链接
我在苹果上找到了这个答案
您可以存储自计时器启动以来经过的时间量......当计时器启动时,将日期存储在 NSDate 变量中。然后当用户切换时……使用 NSDate 类中的方法 timeIntervalSinceNow 来存储经过了多少时间……注意这会给 timeIntervalSinceNow 一个负值。当用户返回时,使用该值设置适当的计时器。