how to pause and resume NSTimer in iphone

前端 未结 7 1641
逝去的感伤
逝去的感伤 2020-12-06 11:07

hello I am developing small gameApp. I need to pause the timer,when user goes to another view [say settings view]. when user comes back to that view , I need to resume the

7条回答
  •  鱼传尺愫
    2020-12-06 11:35

    - (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;
    
    }
    

提交回复
热议问题