Swift 如何使此代码一秒一秒地倒计时?
我有倒计时的代码,但它不是每秒刷新一次。它一加载就暂停。如何使其每秒刷新一次,以便显示每秒倒计时Swift 如何使此代码一秒一秒地倒计时?,swift,swift2,Swift,Swift2,我有倒计时的代码,但它不是每秒刷新一次。它一加载就暂停。如何使其每秒刷新一次,以便显示每秒倒计时 var dateComponents = NSDateComponents() dateComponents.day = 25 dateComponents.month = 12 dateComponents.year = 2015 dateComponents.second = 0 let christmasDay = NSCalendar(ide
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."
您可以将其放入函数中:
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中):
您使用的是计时器还是调度源?如果添加用于此目的的代码,则会有所帮助。你打算问多少次这个问题?对不起?这是我第一次问这个问题。我不知道我在用什么,下面的代码正在运行,不需要其他任何东西。这是正确的方法。作为旁注:将timer属性存储在your Controller实例中(如果存在),并在离开此控制器时调用
if timer.valid{timer.invalidate()}
这将停止计数器,并且在Dealoc/deist上不会出现问题
let timeTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "callEverySecond", userInfo: nil, repeats: true)