【发布时间】:2019-09-11 06:32:59
【问题描述】:
一旦我的按钮被按下,我想禁用我的按钮 24 小时,并在标签上显示倒计时显示倒计时,直到按钮再次处于活动状态。
我已保存等待日期并将其与当前日期进行比较,但我不确定如何以小时、分钟和秒为单位显示剩余时间的倒计时。
let todaysDate = Date()
func set24HrTimer() {
let currentDate = Date()
let newDate = Date(timeInterval: 86400, since: currentDate as Date)
UserDefaults.standard.set(newDate, forKey: "waitingDate")
print("24 hours started")
//disable the button
}
if let waitingDate:Date = UserDefaults.standard.value(forKey: "waitingDate") as? Date {
if (todaysDate.compare(waitingDate as Date) == ComparisonResult.orderedDescending) {
print("show button")
}
else {
print("hide button")
}
}
【问题讨论】:
-
使用 Date 而不是旧的 NSDate,Date 是正确的 swift 类。
-
不要将
value(forKey:)或setValue(_:forKey:)与UserDefaults一起使用。使用正确的 API。如前所述,不要使用NSDate,使用Date。 -
有几种方法可以做到这一点,一种是使用DateComponentsFormatter