سؤال

هنا مشكلتي، عندما أقوم بالنقر فوق الزر "ابدأ"، يعمل مؤقت Timer، عندما انقر فوق الزر "إيقاف"، يتوقف.ومع ذلك، عندما أقوم بالنقر فوق الزر "ابدأ"، عاد إلى الصفر.أرغب في زر البداية للمتابعة حيث توقف الموقت. giveacodicetagpre.

الرجاء المساعدة شكرا لك

هل كانت مفيدة؟

المحلول

You have a problem dealing with state. One state would be that the start button is pushed, but the reset button has not been pushed before it. Another state is that the start button is pushed, and the reset button has been pushed before it. One thing you can do is create an iVar to keep track of this state. So use a BOOL like this:

First declare the iVar:

BOOL resetHasBeenPushed;

Initialize the value to NO.

Then do this

 - (IBAction)onResetPressed {
    stopWatchLabel.text = @”00:00:00:000″;
    resetHasBeenPushed = YES;

Now you need to set it back to NO, at some point, and that might be done in the start method:

- (IBAction)onStartPressed {
    startDate = [NSDate date];
    // Create the stop watch timer that fires every 10 ms
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
    target:self
    selector:@selector(updateTimer)
    userInfo:nil
    repeats:YES];
    resetHasBeenPushed = NO;
}
    }

By the way, if you make your NSDateFormatter in iVar, you don't need to initialize it repeatedly. Movethe following lines to you inti code, or osmewhere it only runs once:

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

UPDATE

Try this:

- (IBAction)onStartPressed {
    if (resetHasBeenPushed== YES) {
        startDate = [NSDate date];  // This will reset the "clock" to the time start is set
    }

    // Create the stop watch timer that fires every 10 ms
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
    target:self
    selector:@selector(updateTimer)
    userInfo:nil
    repeats:YES];
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top