gpt4 book ai didi

ios - 秒表的启动和停止功能不协调 iOS

转载 作者:行者123 更新时间:2023-11-29 02:26:13 25 4
gpt4 key购买 nike

我正在创建秒表,但启动和停止功能不协调。当计时器停止时,它不会从它离开的地方开始。

代码如下所示:

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 秒后再次启动时,它仍应从相同的时间重新开始。但是我的代码,开始和停止时间是不同的,它们是从不同的时间开始的。需要帮助来解决这个问题。

最佳答案

不要在 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

关于ios - 秒表的启动和停止功能不协调 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27506888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com