我正在创建一个秒表,并且没有协调启动和停止功能。当计时器停止时,它不会从它离开的地方开始。
代码如下所示:
self.endDate = [NSDate dateWithTimeIntervalSinceNow:12.0f*60.0f];
-(void)startPressed:(id)sender{
if(!_running){
_running = TRUE;
[sender setTitle:@"Stop" forState:UIControlStateNormal];
if (_stopTimer == nil) {
_stopTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:@selector(changeTimer:)
userInfo:nil
repeats:YES];
}
}else{
_running = FALSE;
[sender setTitle:@"Start" forState:UIControlStateNormal];
[_stopTimer invalidate];
_stopTimer = nil;
}
}
- (void)changeTimer:(NSTimer*)timer {
_timeInterval = [self.endDate timeIntervalSinceNow];
self.timerControl1.minutesOrSeconds = ((NSInteger)_timeInterval)%60;
self.timerControl2.minutesOrSeconds = (NSInteger)(_timeInterval/60.0f);
self.timerControl3.minutesOrSeconds = ((NSInteger)_timeInterval)%60;
}
我知道这是因为timeIntervalSinceNow。但是,如何改变这个?需要一些指导。
问题:
例如,当您停止秒表并在3秒后再次启动秒表时,它仍然会从相同的时间开始。但是我的代码,开始和停止时间都不同,它们是从不同的时间开始的。需要帮助解决这个问题。
答案 0 :(得分:1)
请勿在changeTimer中使用endDate,但仅使用endDate初始化计时器
#import "RimsViewController.h"
@interface RimsViewController ()
@property(weak) IBOutlet UILabel *label;
@property(strong) NSDate *endDate;
@end
@implementation RimsViewController {
BOOL _running;
NSTimeInterval _timeInterval;
NSTimer *_stopTimer;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.endDate = [NSDate dateWithTimeIntervalSinceNow:10*60];
_timeInterval = [self.endDate timeIntervalSinceNow];
}
-(IBAction)startPressed:(id)sender{
if(!_running){
_running = TRUE;
[sender setTitle:@"Stop" forState:UIControlStateNormal];
if (_stopTimer == nil) {
_stopTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(changeTimer:)
userInfo:nil
repeats:YES];
}
}else{
_running = FALSE;
[sender setTitle:@"Start" forState:UIControlStateNormal];
[_stopTimer invalidate];
_stopTimer = nil;
}
}
- (void)changeTimer:(NSTimer*)timer {
_timeInterval -= 1;// [self.endDate timeIntervalSinceNow];
NSUInteger secs = _timeInterval;
int h = (NSUInteger)secs/3600;
secs-=h*3600;
int m = (NSUInteger)secs/60;
secs-=m*60;
int s = secs;
self.label.text = [NSString stringWithFormat:@"%d / %d / %d", h, m, s];
}
@end