4

如何更改此代码使其具有 HH:MM:SS(小时、分钟、秒)?

我是否需要在 .h 或 .m 中添加代码,以便知道是哪一个?

目前它像1、2、3、4等一样上升。

只是为了让你知道我是一个业余爱好者的诱饵,你会复制和过去,所以我知道你的意思。

。H

@interface FirstViewController : UIViewController {
    
    IBOutlet UILabel *time; 
    
    NSTimer *myticker;
    
    //declare baseDate
    NSDate* baseDate; 

}

-(IBAction)stop;
-(IBAction)reset;

@end

.m

#import "FirstViewController.h"

@implementation FirstViewController

-(IBAction)start {
    [myticker invalidate];
    baseDate = [NSDate date];
    myticker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}

-(IBAction)stop;{ 
    
    [myticker invalidate];
    myticker = nil;
}
-(IBAction)reset;{
    
    time.text = @"00:00:00";
}
-(void)showActivity {
    NSTimeInterval interval = [baseDate timeIntervalSinceNow];
    NSUInteger seconds = ABS((int)interval);
    NSUInteger minutes = seconds/60;
    NSUInteger hours = minutes/60;
    time.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes%60, seconds%60];
}
4

1 回答 1

7

首先,在 FirstViewController.h 中声明baseDate变量,如下所示:

@interface FirstViewController : UIViewController {

    IBOutlet UILabel *time; 

    NSTimer *myticker;

    //declare baseDate
    NSDate* baseDate;
}

然后,在FirstViewController.m启动方法中添加baseDate = [NSDate date]如下:

-(IBAction)start {
    [myticker invalidate];
    baseDate = [NSDate date];
    myticker = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}

之后,将您的showActivity方法更改为如下所示:

-(void)showActivity {
    NSTimeInterval interval = [baseDate timeIntervalSinceNow];
    double intpart;
    double fractional = modf(interval, &intpart);
    NSUInteger hundredth = ABS((int)(fractional*100));
    NSUInteger seconds = ABS((int)interval);
    NSUInteger minutes = seconds/60;
    NSUInteger hours = minutes/60;
    time.text = [NSString stringWithFormat:@"%02d:%02d:%02d:%02d", hours, minutes%60, seconds%60, hundredth];
}

另请注意,您必须更改计时器的间隔值,否则您的标签将仅每秒更新一次。

于 2012-02-13T13:27:02.227 回答