我在swift工作,想要每分钟都运行一个函数。我想用倒计时器更新标签,剩下多少分钟,直到下一次更新。
我有一个基本版本
end
当我在应用程序上查看页面时更新,但我希望它每分钟自动更新。 我看过NSTimer,我相信它可以用这个来完成(如图所示:How to make a countdown with NSTimer on Swift)但是我不知道如何在一分钟之后才开始它,只有在一定时间后显示
编辑: 到目前为止,我有以下内容
if let date = newDate {
let formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
formatter.timeZone = NSTimeZone.defaultTimeZone()
let string : NSString = formatter.stringFromDate(date)
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Minute], fromDate: date)
let minute = comp.minute
let remaining : Int = 60 - minute
var mins = "s"
if remaining == 1 {
mins = ""
}
self.refreshInLabel.text = "Refreshes at \(string) - \n \(remaining) minute\(mins) remaining "
}
我想知道是否有更好的方式
答案 0 :(得分:0)
我建议您在每分钟开始使用时启动NSNotification
。
当您收到NSNotification
来电时,会收到如下函数:
var yourTimer = NSTimer()
func callWhenNotificationReceived(){
yourFuncToFire()
yourTimer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: #selector(YourViewController.yourFuncToFire) , userInfo: nil, repeats: true)
}
答案 1 :(得分:-1)
var TotalTime:Int = 0
var timer: NSTimer?
triggerCountDownTimerFor(time:Int)
func triggerCountDownTimerFor(time:Int)
{
totalTime = time
timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: #selector(LoginViewController.updateTimer), userInfo: nil, repeats: true)
}
func updateTimer()
{
let date = NSDate()
let formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
formatter.timeZone = NSTimeZone.defaultTimeZone()
let string : NSString = formatter.stringFromDate(date)
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Minute], fromDate: date)
let minute = comp.minute
let remaining : Int = TotalTime - minute
var mins = "s"
if remaining == 1 {
mins = ""
}
print("Refreshes at \(string) - \n \(remaining) minute\(mins) remaining ")
}