【发布时间】:2015-10-29 14:39:19
【问题描述】:
我正在 Parse 中的多个对象中查询 createdAt 日期。我想创建一个 24 小时(或 48/72 等)倒计时计时器,该计时器从创建对象到 24 小时后倒计时。 (我也在格式化它,并在单元格 UILabel 上显示它。)
示例:如果一个对象是在 19:34:33 创建的,我希望它在 24 小时后过期(或者我在创建后指定多少小时)。最终在 UILabel 上显示距离对象过期的时间。
目前,我正在检索它的创建时间,使其从创建时间开始重复倒计时。
但是,我想制定逻辑,以便在创建对象时需要它,然后显示在 24 小时或 48 小时、72 小时等结束之前还剩多少小时。
编辑
感谢@pulsar,我在下面的描述中添加了几行代码。现在的问题是我只能检索并正确倒计时 1 个对象的 createdAt 日期和时间,因为 仅 查询第一个对象,使所有其他对象都具有在它们各自的 indexPath.row 中与 Parse 中的第一个对象相同的过期 countDown 计时器。
我不知道如何添加所有对象,以便它们都有自己的由 expiresAt 函数触发的 countDown 过期时间。
以下是我查询和格式化它的方式(在 viewDidLoad 中): 这是我问的帮助我格式化日期的问题:Swift countDown timer Logic
请看代码中的 cmets!
var createdAt = object.createdAt
if createdAt != nil {
//assuming this is where i have to set expiration logic?
let calendar = NSCalendar.currentCalendar()
let comps = calendar.components([.Hour, .Minute, .Second], fromDate: createdAt as NSDate!)
let hours = comps.hour * 3600
let minutes = comps.minute * 60
let seconds = comps.second
//I'm adding these two lines below but not sure what to do with them considering I need to add all the objects to an array that will then display it on indexPath.row(s)
let twentyFourHours = NSTimeInterval(60 * 60 * 24)
self.expiresAt = NSDate(timeInterval: twentyFourHours, sinceDate: object.createdAt!!)
self.timerInt.append(hours + minutes + seconds)
//What do i append to the timerInt array? How can i append the objects while triggering the the expiresAt function?
}
这是我的倒计时功能:
func countDown() {
//timerInt is an array where I'm storing the Int values.
for i in 0 ..< timerInt.count {
let hours = timerInt[i] / 3600
//have to somehow add the expiresAt method while looping through each value [i]...?
let minsec = timerInt[i] % 3600
let minutes = minsec / 60
let seconds = minsec % 60
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))
timerInt[i]--
//Im assuming best practice would be to loop through the values in order to change the values/set the expiration time to each object (the expiresAt method). Any ideas of how and where I can add this in this loop so that it reflects the countDown I want to set?
}
self.tableView.reloadData()
}
最后,对于我的 indexPath.row,我将其格式化并显示如下:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cell
//I'm formatting the hours, minutes, seconds. However I'm missing the expiresAt function and I have no clue as to where and how to include it... Should it be here or in the countDown() loop?
let hours = timerInt[indexPath.row] / 3600
let minsec = timerInt[indexPath.row] % 3600
let minutes = minsec / 60
let seconds = minsec % 60
myCell.secondLabel.text = String(format: "%02d:%02d:%02d", hours, minutes, seconds)
return myCell
}
关于如何将其设置为从创建之日起 24/48/72 小时后倒计时的想法?
非常感谢任何和所有帮助!
【问题讨论】:
标签: swift nsdate swift2 countdown