2012-04-21 48 views
6

Tôi đang phát triển một ứng dụng QuiZ. Nó cần một đồng hồ đếm ngược, Trong đó tôi muốn bắt đầu một bộ đếm thời gian lúc 75: 00.00 (mm: ss.SS) và giảm nó xuống 00: 00.00 (mm: ss.SS) bằng cách giảm 1 mili giây. Tôi muốn hiển thị một cảnh báo rằng Time UP! khi thời gian đạt đến 00: 00.00 (mm: ss.SS).NSTimer Giảm thời gian bằng giây/mili giây

Tôi đang hiển thị thời gian bằng cách làm theo bên dưới liên kết

Stopwatch using NSTimer incorrectly includes paused time in display

Trả lời

13

Đây là giải pháp đơn giản cho vấn đề của bạn.

khai báo

@interface ViewController : UIViewController 
{ 
    IBOutlet UILabel * result;  
    NSTimer * timer;     
    int currentTime; 
} 

- (void)populateLabelwithTime:(int)milliseconds; 
-(IBAction)start; 
-(IBAction)pause; 
@end 

Definition

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    currentTime = 270000000; // Since 75 hours = 270000000 milli seconds 


} 

-(IBAction)start{ 
    timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES]; 

} 
-(IBAction)pause{ 
    [timer invalidate]; 

} 
- (void)updateTimer:(NSTimer *)timer { 
    currentTime -= 10 ; 
    [self populateLabelwithTime:currentTime]; 
    } 
- (void)populateLabelwithTime:(int)milliseconds { 
    int seconds = milliseconds/1000; 
    int minutes = seconds/60; 
    int hours = minutes/60; 

    seconds -= minutes * 60; 
    minutes -= hours * 60; 

    NSString * result1 = [NSString stringWithFormat:@"%@%02dh:%02dm:%02ds:%02dms", (milliseconds<[email protected]"-":@""), hours, minutes, seconds,milliseconds%1000]; 
    result.text = result1; 

} 
+1

+1 cho lời giải thích chi tiết. Giữ nó lên. –

+0

Hai nó hoạt động tốt với một số thay đổi ... tôi có xem cuộn, trong đó tôi đang hiển thị thời gian .. Nếu tôi Kéo xem cuộn thời gian không được tính toán (trong nền cũng) ... những gì tôi phải làm. ..? – SriKanth

+1

Thêm mã này để bật hẹn giờ trong khi cuộn ........................................ .......................................... - (IBAction) bắt đầu { timer = [NSTimer scheduleTimerWithTimeInterval: .01 target: self selector: @selector (updateTimer :) userInfo: nil lặp lại: YES]; [[NSRunLoop currentRunLoop] addTimer: timer forMode: NSRunLoopCommonModes]; } –

3

Sử dụng mã sau đây để giảm hẹn giờ.

double dblRemainingTime=60; //1 minute 

if(dblRemainingTime >0) 
{ 
    dblRemainingTime -= 1; 
    int hours,minutes, seconds; 
    hours = dblRemainingTime/3600; 
    minutes = (dblRemainingTime - (hours*3600))/60; 
    seconds = fmod(dblRemainingTime, 60); 
    [lblRemainingTime setText:[NSString stringWithFormat:@"%02d:%02d",minutes, seconds]]; 
} 
else 
     alert('Time up buddy'); 
Các vấn đề liên quan