【问题标题】:How to run coutdown time from remaining time in swift?如何快速从剩余时间运行倒数计时器?
【发布时间】:2016-12-16 21:12:16
【问题描述】:

我有“dd HH:mm:ss”格式的剩余时间,我必须从中运行倒计时时间。我正在使用此代码

func updateCounter() {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd HH:mm:ss"
    let date = dateFormatter.dateFromString(timerString)
    let timeLeft = date!.timeIntervalSinceReferenceDate
    lblTImer.text = timeLeft.time
    lblTImer.font = UIFont.init(name: "Gotham-Book", size: 20)
}

用于更新标签

extension NSTimeInterval {
    var time:String {
        return String(format:"%02d : %02d : %02d : %02d", Int((self/86400)), Int((self/3600.0)%24), Int((self/60.0)%60), Int((self)%60))
    }

}

但我没有得到正确的时间,请纠正我做错了什么。

【问题讨论】:

  • 时间不正确是什么意思?你得到 nil 还是总是 2 天?
  • 如果我在时间字符串中传递“1 22:26:20”,那么我在标签中得到“10957:16:57:22”,就像过去的天数是 1,我得到 10957天

标签: swift nsdate nstimer countdown nstimeinterval


【解决方案1】:

因为您一直在错误地使用NSDateFormatter。在你的timerString 中没有年份和月份,只有小时、分钟、秒。另一方面,您忘记调整时区。

您的timeString 表示持续时间,以秒为单位并格式化为day hour:minute:second 样式。据我所知,Cocoa / UITouch 没有为此提供合适的格式化程序。但是构建一个很简单:

extension NSTimeInterval {
    init(fromString str: String) {
        let units: [Double] = [1, 60, 3600, 86400]
        let components = str.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: " :")).reverse()

        self = zip(units, components)
                .map { $0 * (Double($1) ?? 0) }
                .reduce(0, combine: +)
    }

    var time:String {
        return String(format:"%02d : %02d : %02d : %02d", Int((self/86400)), Int((self/3600.0)%24), Int((self/60.0)%60), Int((self)%60))
    }
}


let timerString = "1 22:26:20"

let timeLeft = NSTimeInterval(fromString: "1 22:26:20")
print(timeLeft)         // 167180.0
print(timeLeft.time)    // 01 : 22 : 26 : 20

【讨论】:

  • 谢谢,但是我如何将它与计时器一起使用,它会改变 timeLeft 值?到目前为止,它只给出“01:22:26:20”
  • 这是一个不同的问题。您在这里问的是如何将字符串转换为秒数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 1970-01-01
相关资源
最近更新 更多