gpt4 book ai didi

swift - 如何让这段代码秒到秒倒计时?

转载 作者:行者123 更新时间:2023-11-28 13:05:20 25 4
gpt4 key购买 nike

我有这段倒计时代码,但它不会每秒刷新一次。它只是在加载后立即暂停。如何让它每秒刷新一次以显示秒到秒的倒计时?

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 中):

let timeTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "callEverySecond", userInfo: nil, repeats: true)

关于swift - 如何让这段代码秒到秒倒计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33000101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com