【问题标题】:How to make NSTimer show Month : Weeks : Days如何使 NSTimer 显示月:周:天
【发布时间】:2015-08-19 19:35:21
【问题描述】:

我正在尝试让计时器显示以下内容 - 年:月:周:日:小时:分钟:秒:毫秒。

我不希望它在秒数达到 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
    }
}

问题是它只显示秒。我怎样才能让它显示所有其余部分? (就像我上面写的那样。)

【问题讨论】:

    标签: ios swift nstimer


    【解决方案1】:

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

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

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

    【讨论】:

    • NSDateComponentsFormatter 也有月份和年份吗?
    • @MikeRally 另外两个注意事项: 1. 不要自己增加计时器(因为不能保证确切的时间间隔)。 2. 小心使用较大单位的时间间隔(例如,1 个月等于 31 天吗?30 天?28 天?还有,夏令时呢?)所以,相反,我可能建议捕获开始日期和结束日期,然后改用stringFromDate:toDate: 方法。解决这两个问题。
    • 酷!我还没有发现NSDateComponentsFormatter(已投票)。感谢您提请我注意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 2019-02-05
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多