NSTimer到4位标签更新

时间:2015-08-14 13:58:08

标签: ios swift stopwatch

我刚刚制作了一个带有教程的秒表,但我想做的是将我的00:00标签更新为1秒增加,如00:01,00:02:00:03,并在几分钟内做同样的事情。无论如何这样做?提前谢谢!

3 个答案:

答案 0 :(得分:2)

然后你必须得到一个开始计数的日期,从那个特定事件发生的当前日期,让我们说我们将在视图出现时启动计时器,所以实现vi​​ewWillAppear如下: / p>

var currentDate = NSDate()

override func viewWillAppear(animated: Bool) {

    currentDate = NSDate()

    var timer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateLabel", userInfo: nil, repeats: true)

    timer.fire()

}

并实现updateLabel函数:

func updateLabel() {

    dispatch_async(dispatch_get_main_queue(), { () -> Void in

        var elapsedSeconds: NSTimeInterval = -self.currentDate.timeIntervalSinceNow

        let minutes: Int = Int(elapsedSeconds)/60
        let seconds: Int = Int(elapsedSeconds) - (minutes*60)

        self.timeLabel.text = String(format: "%02d:%02d", minutes, seconds)

    })

}

答案 1 :(得分:0)

格式化时间过后,NSDateComponentsFormatter是另一种选择:

var start: CFAbsoluteTime!

override func viewDidLoad() {
    super.viewDidLoad()

    start = CFAbsoluteTimeGetCurrent()
    NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "handleTimer:", userInfo: nil, repeats: true)
}

lazy var formatter: NSDateComponentsFormatter = {
    let _formatter = NSDateComponentsFormatter()
    _formatter.allowedUnits = .CalendarUnitMinute | .CalendarUnitSecond
    _formatter.zeroFormattingBehavior = .Pad
    return _formatter
}()

func handleTimer(timer: NSTimer) {
    let elapsed = CFAbsoluteTimeGetCurrent() - start
    label.text = formatter.stringFromTimeInterval(elapsed)
}

不可否认,这将为您提供0:00格式,而不是00:00格式的时间。

答案 2 :(得分:-1)

这是Objective-C,但你会得到这个想法:

django.contrib.admin.utils

和我的Localizable.strings:

-(void) updateTotalTime
{
int forHours = timeInSeconds / 3600, 
remainder = timeInSeconds % 3600, 
forMinutes = remainder / 60, 
forSeconds = remainder % 60;

[elapsedTime setString:[NSString stringWithFormat:NSLocalizedString(@"elapsedTime", nil)
                        ,forHours
                        ,forMinutes
                        ,forSeconds]];

}