如何在 Swift 中设置计时器
How to set up a timer in Swift
我正在尝试找出跟踪我制作的计时器时间的最佳方法。我希望计时器在应用程序未打开时也能工作。
我可以用伪代码说出我的想法,但我所知道的 Swift 不足以实现它。当按下 startStopButton 时,我可能想要设置一个 NSDate。然后,每一秒,我都希望将一个新的 NSDate 与原始 NSDate 进行比较,以确定已经过去了多少秒。这样,如果用户离开应用程序并返回,它只会检查原始时间戳并将其与现在进行比较。然后,我将该秒数放入我已经设置的变量中以按照我想要的方式进行操作。这是我目前所拥有的:
var timer = NSTimer()
var second = 00.0
func timerResults() {
second += 1
let secondInIntForm = Int(second)
let (h,m,s) = secondsToHoursMinutesSeconds(secondInIntForm)
}
@IBAction func startStopButton(sender: AnyObject) {
date = NSDate()
moneyEverySecond = (people*wage)/3600
if updatingSymbol.hidden == true { //Start the timer
sender.setTitle("STOP", forState: UIControlState.Normal)
updatingSymbol.hidden = false
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timerResults"), userInfo: nil, repeats: true)
} else { //Stop the timer
sender.setTitle("START", forState: UIControlState.Normal)
updatingSymbol.hidden = true
//***stop the timer
timer.invalidate()
}
}
如果有人能提供帮助,那就太好了。
通过userInfo
参数传递定时器的开始时间:
@IBAction func startStopButton(sender : AnyObject) {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.timerResults(_:)) , userInfo: NSDate(), repeats: true)
}
func timerResults(timer: NSTimer) {
let timerStartDate = timer.userInfo as! NSDate
let seconds = Int(NSDate().timeIntervalSinceDate(timerStartDate))
print(seconds)
}
(我删除了你的部分功能,因为它们与问题无关)
我正在尝试找出跟踪我制作的计时器时间的最佳方法。我希望计时器在应用程序未打开时也能工作。
我可以用伪代码说出我的想法,但我所知道的 Swift 不足以实现它。当按下 startStopButton 时,我可能想要设置一个 NSDate。然后,每一秒,我都希望将一个新的 NSDate 与原始 NSDate 进行比较,以确定已经过去了多少秒。这样,如果用户离开应用程序并返回,它只会检查原始时间戳并将其与现在进行比较。然后,我将该秒数放入我已经设置的变量中以按照我想要的方式进行操作。这是我目前所拥有的:
var timer = NSTimer()
var second = 00.0
func timerResults() {
second += 1
let secondInIntForm = Int(second)
let (h,m,s) = secondsToHoursMinutesSeconds(secondInIntForm)
}
@IBAction func startStopButton(sender: AnyObject) {
date = NSDate()
moneyEverySecond = (people*wage)/3600
if updatingSymbol.hidden == true { //Start the timer
sender.setTitle("STOP", forState: UIControlState.Normal)
updatingSymbol.hidden = false
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timerResults"), userInfo: nil, repeats: true)
} else { //Stop the timer
sender.setTitle("START", forState: UIControlState.Normal)
updatingSymbol.hidden = true
//***stop the timer
timer.invalidate()
}
}
如果有人能提供帮助,那就太好了。
通过userInfo
参数传递定时器的开始时间:
@IBAction func startStopButton(sender : AnyObject) {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.timerResults(_:)) , userInfo: NSDate(), repeats: true)
}
func timerResults(timer: NSTimer) {
let timerStartDate = timer.userInfo as! NSDate
let seconds = Int(NSDate().timeIntervalSinceDate(timerStartDate))
print(seconds)
}
(我删除了你的部分功能,因为它们与问题无关)