使用 NSTimer 表示 HH:MM:SS?
如何更改此代码,使其具有 HH:MM:SS(小时、分钟、秒)?
我是否需要在 .h 或 .m 中添加代码以便我知道是哪一个?
目前它的价格上涨了 1、2、3、4 等。
只是为了让你知道我是业余爱好者的诱饵,你可以复制并过去,这样我就知道你的意思了。
.h.m
@interface FirstViewController : UIViewController {
IBOutlet UILabel *time;
NSTimer *myticker;
//declare baseDate
NSDate* baseDate;
}
-(IBAction)stop;
-(IBAction)reset;
@end
#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];
}
How can I change this code so it has HH:MM:SS (hours, minutes, seconds)?
Do I need to add code in .h or .m so I known which one?
At the moment it goes up like 1, 2, 3, 4 etc.
Just to let you known I'm bait of a amateur would you copy and past so I known what you mean.
.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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,在 FirstViewController.h 中声明 baseDate 变量,如下所示:
然后,在 FirstViewController.m start 方法中添加
baseDate = [NSDate date]
像这样:之后,将您的 showActivity 方法更改为如下所示:
另请注意,您必须更改计时器的间隔值,否则您的标签将每秒仅更新一次。
First, declare baseDate variable in your FirstViewController.h, like this:
Then, in the FirstViewController.m start method add
baseDate = [NSDate date]
like this:After that, change your showActivity method to look like this:
Also note, that you will have to change the interval value for your timer, otherwise your label will only be updated once a second.