如何让NSTimer显示月份:周:天

时间:2015-08-19 19:35:21

标签: ios swift nstimer

我试图让计时器显示以下内容 - 年:月:周:天:小时:分钟:秒:毫秒。

我不希望它显示分钟直到秒数达到60,并且相同的数小时等等。例如:如果它持续3天4小时39分3秒和43毫秒,它不应该显示月份或年份,因为到目前为止它们都是0。

这就是我所拥有的。

@IBOutlet weak var timeLabel: UILabel!
var timerCount = 0
var timerRuning = false
var timer = NSTimer()

func counting() {
    timerCount++
    timeLabel.text = "\(timerCount)"
}

@IBAction func startTime(sender: UIButton)
{
    if timerRuning == false {
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: ("counting"), userInfo: nil, repeats: true)
        timerRuning = true
    }
}

@IBAction func finishTime(sender: UIButton)
{
    if timerRuning == true {
        timer.invalidate()
        timerRuning = false
    }
}

问题是它只显示秒数。如何让它显示所有其余的? (就像我上面写的那样。)

1 个答案:

答案 0 :(得分:2)

iOS 8.0中引入了一个新的类NSDateComponentsFormatter,它可以将秒数格式化为可读的时间字符串。

func counting() {
  timerCount++
  let formatter = NSDateComponentsFormatter()
  formatter.unitsStyle = .Full
  timeLabel.text = formatter.stringFromTimeInterval(NSTimeInterval(timerCount))
}

但有一个限制:它不会考虑小于秒的单位。