2012-02-28 64 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

一個時間間隔將增加,像1,2,3,4,5等

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

下一次,我們稱之爲updateTimer功能totalTimeInterval將爲1 = 1 + 2,所以totalTimeInterval將是3.

所以,如果我們顯示totalTimeInterval,秒將是1,3,6,....等。

  1. 首先,你需要NSTimeInterval totalTimeInterval和NSTimeInterval一個時間間隔變量一流水平

  2. updateTimer方法,需要更換下面的代碼。

    timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
    timeInterval += totalTimeInterval; 
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 
    
  3. 然後onStopPressed方法和下面的代碼。

    totalTimeInterval = timeInterval; 
    

感謝。