2012-02-28 8 views
0

こんにちは私は私のアプリでストップウォッチを持っています。Xcodeのストップウォッチの問題

私はストップウォッチでスタート、ストップ、リセットボタンを持っています。

停止とリセットボタンはスタートは、ソートの作品

を働きます。

ユーザが最初にスタートボタンをクリックすると、ストップウォッチが開始されます。彼らが停止ボタンをクリックし、スタートボタンをクリックすると、ストップウォッチが再び始まります。

私は何が欠けていますか(下記のコード)?

の.h

IBOutlet UILabel *stopWatchLabel; 
    NSTimer *stopWatchTimer; // Store the timer that fires after a certain time 
    NSDate *startDate; // Stores the date of the click on the start button 
    @property (nonatomic, retain) IBOutlet UILabel *stopWatchLabel; 
    - (IBAction)onStartPressed; 
    - (IBAction)onStopPressed; 
    - (IBAction)onResetPressed; 
    - (void)updateTimer 

.M

- (void)updateTimer{ 

    NSDate *currentDate = [NSDate date]; 
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"HH:mm:ss:SSS"]; 
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 
    NSString *timeString=[dateFormatter stringFromDate:timerDate]; 
    stopWatchLabel.text = timeString; 

    } 

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

    - (IBAction)onStopPressed { 
    [stopWatchTimer invalidate]; 
    stopWatchTimer = nil; 
    [self updateTimer]; 
    } 

    - (IBAction)onResetPressed { 
    stopWatchLabel.text = @"00:00:00:000"; 
    } 

すべてのヘルプは素晴らしいことです。あなたは、スタート・ストップ・アクション中に経過時間を記憶している上記のコードで

乾杯

答えて

1

。これを行うには、クラスレベルでNSTimeInterval totalTimeInterval変数が必要です。最初またはリセットボタンを押すとその値は0に設定されますupdateTimerメソッドでは、次のコードを置き換える必要があります。

NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
totalTimeInterval += timeInterval; 
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:totalTimeInterval ]; 

おかげで、

0

時間間隔は、我々はupdateTimer機能totalTimeIntervalは1 = 1となります呼び出すなど、1,2,3,4,5のように、

totalTimeInterval = totalTimeInterval + timeInterval -> 0 = 0 + 1 

次の時間が長くなります+ 2、totalTimeIntervalは3になります。

したがって、totalTimeIntervalを表示すると、秒は1、3、6、...などになります。

  1. まず、クラスレベルで使用すると、次のコード交換する必要があります

  2. updateTimer方法をNSTimeInterval totalTimeIntervalとNSTimeInterval時間間隔変数が必要になります。

    timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
    timeInterval += totalTimeInterval; 
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 
    
  3. 、次いでonStopPressed方法及び次のコード。

    totalTimeInterval = timeInterval; 
    

感謝。