秒表启动按钮可重置计时器

时间:2014-04-15 17:37:26

标签: ios objective-c timer stopwatch

我正在制作一个基本的秒表,但是,每次启动计时器时,单击停止,然后再次开始想要继续我的计时器,时钟重新开始为0.我不太清楚该做什么,因为我刚拿起obj-c / Xcode。

#import "StopwatchViewController.h"

bool stopPressed = false;
bool startPressed = false;
int startsPressed = 0;
NSTimeInterval totalTimeInterval;

@interface StopwatchViewController ()

@property (strong, nonatomic) NSTimer *stopWatchTimer; // Store the timer that fires after a certain time
@property (strong, nonatomic) NSDate *startDate; // Stores the date of the click on the start button



@end

@implementation StopwatchViewController

- (void)updateTimer
{
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate: self.startDate];
    totalTimeInterval = timeInterval;
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:totalTimeInterval];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"HH:mm:ss.SSS"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];

     NSString *timeString = [dateFormatter stringFromDate:timerDate];
     self.stopwatchLabel.text = timeString;



}



- (IBAction)onStartPressed:(id)sender
{
    if(startsPressed < 1) {
        if(startPressed) return;
        startPressed = true;
        stopPressed =false;
        self.startDate = [NSDate date];

        //create the stop watch timer that fires every 100ms
        self.stopWatchTimer =
        [NSTimer scheduledTimerWithTimeInterval:1.0/100.0
                                     target:self
                                selector:@selector(updateTimer)
                                   userInfo:nil
                                    repeats:YES];
    } else {

        startPressed = true;
        stopPressed = false;

    }
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)onStopPressed:(id)sender {
    if(stopPressed) return;
    stopPressed = true;
    startPressed = false;
    [self.stopWatchTimer invalidate];
    self.stopWatchTimer  = nil;
    [self updateTimer];
}

- (IBAction)onResetPressed:(id)sender {
    if(stopPressed == false) return;
    self.stopWatchTimer = 0;
    NSString *timeString = @"00:00:00.000";
    self.stopwatchLabel.text = timeString;
}


@end

我目前正处于我的起点

#import "StopwatchViewController.h"

    bool stopPressed = false;
    bool startPressed = false;
    int startsPressed = 0;
    NSTimeInterval totalTimeInterval;

    @interface StopwatchViewController ()

    @property (strong, nonatomic) NSTimer *stopWatchTimer; // Store the timer that fires after a certain time
    @property (strong, nonatomic) NSDate *startDate; // Stores the date of the click on the start button
    @property (nonatomic, strong) NSDate *pauseDate;

    @end

    @implementation StopwatchViewController

    - (void)updateTimer
    {
        NSDate *currentDate = [NSDate date];
        NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate: self.startDate];
        totalTimeInterval = timeInterval;
        NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:totalTimeInterval];

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat: @"HH:mm:ss.SSS"];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];

        NSString *timeString = [dateFormatter stringFromDate:timerDate];
        self.stopwatchLabel.text = timeString;



    }



    - (IBAction)onStartPressed:(id)sender
    {
    //    if(startsPressed < 1) {
    //        if(startPressed) return;
    //        startPressed = true;
    //        stopPressed =false;
    //        self.startDate = [NSDate date];
    //        
    //        //create the stop watch timer that fires every 100ms
    //        self.stopWatchTimer =
    //        [NSTimer scheduledTimerWithTimeInterval:1.0/100.0
    //                                         target:self
    //                                       selector:@selector(updateTimer)
    //                                       userInfo:nil
    //                                        repeats:YES];
    //    } else {
    //        
    //        startPressed = true;
    //        stopPressed = false;
    //        
    //    }

        if(startsPressed < 1) {
            if( ! _startDate) {
                self.startDate = [NSDate date];
            }
            else {
                if(_pauseDate) {
                    NSTimeInterval startTime = _startDate.timeIntervalSince1970;
                    NSTimeInterval pauseTime = _startDate.timeIntervalSince1970;

                    // the actual elapsed time before we paused
                    NSTimeInterval elapsedTime = pauseTime - startTime;

                    // set a new start time to match our elapsed time.
                    NSTimeInterval currentTime = [NSDate date].timeIntervalSince1970;
                    NSTimeInterval newStartTime = currentTime - elapsedTime;
                    _startDate = [NSDate dateWithTimeIntervalSince1970:newStartTime];
                    _pauseDate = nil;
                }
            }


        }
    }


    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization
        }
        return self;
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
    }

    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }


    - (IBAction)onStopPressed:(id)sender {
        if(stopPressed) return;
        _pauseDate = [NSDate date];
        stopPressed = true;
        startPressed = false;
        [self.stopWatchTimer invalidate];
        self.stopWatchTimer  = nil;
        [self updateTimer];
    }

    - (IBAction)onResetPressed:(id)sender {
        if(stopPressed == false) return;
        _startDate = nil;
        _pauseDate = nil;
        self.stopWatchTimer = 0;
        NSString *timeString = @"00:00:00.000";
        self.stopwatchLabel.text = timeString;
    }


    @end

2 个答案:

答案 0 :(得分:0)

每次点击&#34;开始&#34;,此代码都会运行:

self.startDate = [NSDate date];

这会重置您正在使用的开始时间。将其移出某处,使其只发生一次,而不是每次启动计时器时,我认为结果将更接近您想要的结果。也许你可以存储一个额外的BOOL,它会在第一次启动计时器时被切换。

修改:

我忽略了Stonz2提出的非常好的观点。这样做会在启动备份后导致跳过时间。为了解决此问题,您需要在停止计时器时存储单独的NSDate,以表示暂停的&#34;暂停&#34;时间。然后,当您再次启动计时器备份时,您需要添加&#34;暂停&#34;时间到了#34;开始&#34;时间,以便继续流动。

EDIT2:

我把它扔进了一个项目,这里有一些工作代码。

我添加了一个额外的属性:

@property (nonatomic, strong) NSDate *pauseDate;

onStopPressed:中,我添加了此内容以初始化暂停时间:

_pauseDate = [NSDate date];

然后,在onStartPressed:中,我添加了以下代码以确保startDate的单个初始化并进行数学计算以获得暂停后经过的时间:

    // if we have a start date, don't initialize again
    if(! _startDate)
    {
        self.startDate = [NSDate date];
    }
    else
    {
        if(_pauseDate)
        {
            NSTimeInterval startTime = _startDate.timeIntervalSince1970;
            NSTimeInterval pauseTime = _pauseDate.timeIntervalSince1970;

            // The actual elapsed time before we paused.
            NSTimeInterval elapsedTime = pauseTime - startTime;

            // Set a new start time to match our elapsed time.
            NSTimeInterval currentTime = [NSDate date].timeIntervalSince1970;
            NSTimeInterval newStartTime = currentTime - elapsedTime;
            _startDate = [NSDate dateWithTimeIntervalSince1970:newStartTime];
            _pauseDate = nil;
        }
    }

另外,为了使您的重置工作正常,在onResetPressed:中您需要添加:

_startDate = nil;
_pauseDate = nil;

刚试过这个,它就像一个冠军。

编辑3:根据评论主题的完整方法

- (IBAction)onStartPressed:(id)sender
{
    if(startsPressed < 1) {
        if(startPressed) return;
        startPressed = true;
        stopPressed =false;
        if(! _startDate)
        {
            self.startDate = [NSDate date];
        }
        else
        {
            if(_pauseDate)
            {
                NSTimeInterval startTime = _startDate.timeIntervalSince1970;
                NSTimeInterval pauseTime = _pauseDate.timeIntervalSince1970;
                NSTimeInterval elapsedTime = pauseTime - startTime;
                NSTimeInterval currentTime = [NSDate date].timeIntervalSince1970;
                NSTimeInterval newStartTime = currentTime - elapsedTime;
                _startDate = [NSDate dateWithTimeIntervalSince1970:newStartTime];
                _pauseDate = nil;
            }
        }

        //create the stop watch timer that fires every 100ms
        self.stopWatchTimer =
        [NSTimer scheduledTimerWithTimeInterval:1.0/100.0
                                         target:self
                                       selector:@selector(updateTimer)
                                       userInfo:nil
                                        repeats:YES];
    } else {

        startPressed = true;
        stopPressed = false;

    }
}

答案 1 :(得分:0)

这是因为您在self.startDate方法中重置了onStartPressed。仅在viewDidLoad:onResetPressed:

中执行此操作