简体   繁体   English

已用计时器未启动

[英]Elapsed Timer not starting

I am building an elapsed timer and while the code gives no errors the timer does not start. 我正在建立一个经过的计时器,而代码没有给出错误,则计时器无法启动。

I am using two ViewControllers, one called Stopwatch which has the start stop function in it under the class Stopwatch() and then a regular ViewController with the rest in it. 我正在使用两个ViewController,一个叫做Stopwatch,它在Stopwatch()类下具有启动停止功能,然后是一个普通的ViewController,其中包含其余的控件。

主故事板 按钮和插座连接

View Controller Code: 查看控制器代码:

import UIKit

class ViewController: UIViewController {

let watch = Stopwatch()

@IBOutlet weak var elapsedTimeLabel: UILabel!

@IBAction func startButton(_ sender: Any) {
    Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.updateElapsedTimeLabel), userInfo: nil, repeats: true)

    watch.start()
}

@IBAction func stopButton(_ sender: Any) {
    watch.stop()
}

@objc func updateElapsedTimeLabel (timer : Timer) {
    if watch.isRunning {
        let minutes = Int (watch.elapsedTime/60)
        let seconds = watch.elapsedTime.truncatingRemainder(dividingBy: 60)
        let tenOfSeconds = (watch.elapsedTime * 10).truncatingRemainder(dividingBy: 10)
        elapsedTimeLabel.text = String (format: "%02d:%02d:%02d", minutes, seconds, tenOfSeconds)
    } else {
        timer.invalidate()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

override var prefersStatusBarHidden: Bool {
    return true
}
}

The Stopwatch View Controller code: 秒表视图控制器代码:

import Foundation

class Stopwatch {

private var startTime : Date?

var elapsedTime: TimeInterval {
    if let startTime = self.startTime {
        return -startTime.timeIntervalSinceNow
    } else {
        return 0
    }
}
var isRunning: Bool {
    return startTime != nil
}

func start() {
    startTime = Date()
}

func stop() {
    startTime = nil
}
}

There is nothing at all coming in the debug window, so not sure what the issue is, I reconnected the buttons over and over so it's not that. 调试窗口中什么都没有,所以不确定是什么问题,我一遍又一遍地重新连接了按钮,事实并非如此。 I also get no other errors in the code as mentioned above. 如上所述,我在代码中也没有得到其他错误。

Can anyone shed some light on this. 任何人都可以阐明这一点。 Maybe I am using the wrong #selector or I am doing the updateElapsedTimeLabel minutes, seconds, tenOfSeconds calculations wrong. 也许我使用了错误的#selector或我在执行updateElapsedTimeLabel分钟,秒,tenOfSeconds计算错误。 Not sure. 不确定。 Thanks for having a look. 感谢您的浏览。

If you Option-click on seconds and tenOfSeconds you will find that one is of type TimeInterval (ie Double ) and the other is of type Double . 如果在Option上单击secondstenOfSeconds您会发现一个类型为TimeInterval (即Double ),另一个类型为Double So your format specifier of %02d was wrong. 因此,您的%02d格式说明符是错误的。 In C, a mismatch between the format specifier and the argument is undefined behavior. 在C语言中,格式说明符和参数之间的不匹配是未定义的行为。 Swift doesn't say how it handles that but I guess it will ignore the argument. Swift并未说明如何处理,但我想它将忽略该参数。

To fix it, change your format specifier for the last 2 components to %02.f : 要解决此问题,请将最后2个组件的格式说明符更改为%02.f

let minutes = Int(watch.elapsedTime/60)
let seconds = watch.elapsedTime.truncatingRemainder(dividingBy: 60)
let tenOfSeconds = (watch.elapsedTime * 100).truncatingRemainder(dividingBy: 100) // fixed the math here
elapsedTimeLabel.text = String(format: "%02d:%02.f:%02.f", minutes, seconds, tenOfSeconds)

But why not use a DateFormatter to make your life simpler: 但是,为什么不使用DateFormatter来简化您的生活:

class ViewController: UIViewController {
    private let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "mm:ss:SS"
        return formatter
    }()

    @objc func updateElapsedTimeLabel (timer : Timer) {
        if watch.isRunning {
            elapsedTimeLabel.text = formatter.string(from: Date(timeIntervalSince1970: watch.elapsedTime))
        } else {
            timer.invalidate()
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM