Swift 4: TimeInterval 每次设置为随机数

Swift 4: TimeInterval set to random number each time

我正在尝试复制 iPhone 上的默认时钟应用程序,以便更好地学习 swift 并适应 iOS 开发的不同部分。

我目前正在开发应用程序的计时器部分。 我有一个 DatePicker 来获取日期,并且在计时器启动时将 countdownDuration 属性 分配给 TimeInterval。 然而,这每次都会给我一个随机值(似乎总是在 80.0-120.0 左右)

我完全理解我的 TimeIntervals 概念可能是错误的,但根据我在网上和开发者文档中阅读的内容,我的概念是正确的吗?

这是我用来 运行 计时器的代码:

@IBOutlet weak var datePicker:UIDatePicker!

var IsTimerRunning:Bool = false;
var TimerDuration:TimeInterval = 0;

var timer:Timer?;

//Called every second when timer is running
@objc func onTimerFires() {
    TimerDuration = TimerDuration - 1.0;
    print (TimerDuration);
    if (TimerDuration <= 0.0) {
        EndTimer();
    }
}

func EndTimer() {
    timer?.invalidate();
    IsTimerRunning = false;
}

//Start button pressed
@IBAction func StartButtonPressed() {
    if (IsTimerRunning == false) {
        TimerDuration = datePicker.countDownDuration;

        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)

        IsTimerRunning = true;
    }
}

几个注意事项:

  1. 确保您的日期选择器的模式为 countDownTimer。正如 the documentation 所说:

    If the mode of the date picker is not UIDatePicker.Mode.countDownTimer, this value [countDownDuration] is undefined...

  2. 如果您在 IB 上添加了这个,您可能需要将 "date" 属性 设置为 "Custom"。正如文档警告我们的那样:

    Note

    When you use Interface Builder to set the Mode attribute to Count Down Timer and specify a value for the timer attribute, your date picker may not respect the Timer attribute value when you build and run your project. If this happens, return to the Attributes inspector for the date picker, select Custom in the Date pop-up menu (you can ignore the associated value), and rebuild your project.

    我注意到非常奇怪的 countDownDuration 值,直到我在 IB 中为 "Date" 弹出菜单选择 "custom"。