我有这个代码用于倒计时,但它不会每秒刷新一次。它只是在加载时暂停。如何让它每秒刷新一次,以显示第二到第二倒计时?
var dateComponents = NSDateComponents()
dateComponents.day = 25
dateComponents.month = 12
dateComponents.year = 2015
dateComponents.second = 0
let christmasDay = NSCalendar(identifier: NSCalendarIdentifierGregorian)!.dateFromComponents(dateComponents)!
let durationDateComponents = NSCalendar(identifier: NSCalendarIdentifierGregorian)!.components( [.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: NSDate(), toDate: christmasDay, options: [])
minUntilHoliday.text = "\(durationDateComponents.minute) months and"
secUntilHoliday.text = "\(durationDateComponents.second) days."
答案 0 :(得分:2)
您可以将其放入函数中:
func callEverySecond() {
var dateComponents = NSDateComponents()
dateComponents.day = 25
dateComponents.month = 12
dateComponents.year = 2015
dateComponents.second = 0
let christmasDay = NSCalendar(identifier: NSCalendarIdentifierGregorian)!.dateFromComponents(dateComponents)!
let durationDateComponents = NSCalendar(identifier: NSCalendarIdentifierGregorian)!.components( [.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: NSDate(), toDate: christmasDay, options: [])
minUntilHoliday.text = "\(durationDateComponents.minute) months and"
secUntilHoliday.text = "\(durationDateComponents.second) days."
}
然后,使用NSTimer(在viewDidLoad中)调用该函数:
let timeTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "callEverySecond", userInfo: nil, repeats: true)