如何在ios中显示活动的时间

时间:2015-07-21 12:41:19

标签: ios objective-c time

在我的iOS应用中,我必须以HH:MM:SS格式创建一个数字计时器(不是系统时间),该计时器应该从00:00:00 button开始,我可以制作使用任何标准库来做到这一点?或者我应该写自己的逻辑?

3 个答案:

答案 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