在我的iOS应用中,我必须以HH:MM:SS
格式创建一个数字计时器(不是系统时间),该计时器应该从00:00:00
button
开始,我可以制作使用任何标准库来做到这一点?或者我应该写自己的逻辑?
答案 0 :(得分:1)
所以你可以做的一件事就是创建一个计时器并记住你创建计时器的时间。
@IBAction func buttonTapped() {
// Store date / time in which you tapped the button
self.initialDate = NSDate()
// Create timer that fires every second starting now (scheduled), and repeats
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timerTick"), userInfo: nil, repeats: true)
}
然后,当你有初始的东西时,你可以做timerTick
方法。在这里,您获得当前日期,在存储的日期和当前日期之间做差异并显示它:
func timerTick() {
// Get calendar and components of the dates in interval <initialDate, currentDate>
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitSecond | .CalendarUnitMinute | .CalendarUnitHour, fromDate: self.initialDate, toDate: NSDate(), options: NSCalendarOptions.allZeros)
// In this point you have minutes, seconds and hours, you can just present it
// "%02d:%02d:%02d" in format means "number, always at least 2 numbers, fill with zeroes if needed")
self.label.text = String(format: "%02d:%02d:%02d", components.hour, components.minute, components.second)
}
如果您想停止计时器,可以通过拨打self.timer.invalidate()
希望它有所帮助!
答案 1 :(得分:0)
iOS Foundation框架包含NSDateFormatter
类(以及NSDate
数据类型),它就是这样做的。
答案 2 :(得分:0)
在.m文件中添加以下属性:
#import "MyVC.h"
@interface MyVC()
@property (strong, nonatomic) NSTimer* timer; // our timer
@property (nonatomic) NSInteger secondsPassed; // how many seconds have been passed since the start of the timer
@end
viewDidLoad
或您IBAction
的{{1}}方法:
UIButton
每秒都会调用此方法来更新UILabel
- (void)viewDidLoad {
[super viewDidLoad];
self.myLabel.text = @"00:00:00"; // start text
// invoke updateTimer every second
self.timer = [NSTimer scheduledTimerWithTimeInterval: 1.0
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats: YES];
}
或者您可以使用MZTimerLabel