xcode – 使用NSTimer for HH:MM:SS?
发布时间:2020-12-14 17:59:01 所属栏目:百科 来源:网络整理
导读:如何更改此代码,使其具有HH:MM:SS(小时,分钟,秒, 你能告诉我是否需要在.h或.m中添加代码以便我知道哪一个 此刻它会像1,2,3,4等一样上升 嗨,大家只是为了让你知道我是一个业余的诱饵你会复制和过去所以我知道你的意思谢谢 亲切的问候 保罗 .H @interface Fi
如何更改此代码,使其具有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]; } 解决方法
首先,在FirstViewController.h中声明baseDate变量,如下所示:
@interface FirstViewController : UIViewController { IBOutlet UILabel *time; NSTimer *myticker; //declare baseDate NSDate* baseDate; } 然后,在FirstViewController.m start方法中添加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",seconds%60,hundredth]; } 另请注意,您必须更改计时器的间隔值,否则您的标签每秒只会更新一次. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |