【问题标题】:How to set up a timer in Swift如何在 Swift 中设置计时器
【发布时间】:2016-05-09 04:33:07
【问题描述】:

我正在尝试找出为我制作的计时器记录时间的最佳方法。我希望计时器在应用程序未打开时也能工作。

我可以用伪代码说出我的想法,但我对 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()
    }
}

如果有人能帮忙,那就太好了。

【问题讨论】:

    标签: swift timer nsdate


    【解决方案1】:

    通过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)
    }
    

    (我删除了您的某些功能,因为它们与问题无关)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 2010-10-02
      • 2021-09-22
      • 2011-06-03
      • 1970-01-01
      相关资源
      最近更新 更多