简体   繁体   English

在倒数计时器(swift3)之前添加倒数计时器

[英]add a countdown timer before a countdown timer (swift3)

In my code if you press the startButton countdown goes from 60 - 0 . 在我的代码中,如果您按下startButton,则倒数从60-0开始。 All I want to do is have a countdown from 3 - 0 then countdown from 60 - 0. Think of it mark, set, go then start the countdown timer from 60 seconds to 0. 我要做的就是从3-0开始倒数​​,然后从60-0开始倒数​​。考虑一下它的标记,设置,运行,然后将倒数计时器从60秒设置为0。

 import UIKit
class ViewController: UIViewController {

@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var timerLabel: UILabel!

var seconds = 60
var timer = Timer()
var isTimerRunning = false
var resumeTapped = false

@IBAction func startButtonTapped(_ sender: UIButton) {
    if isTimerRunning == false {
        runTimer()
        self.startButton.isEnabled = false
    }
}

func runTimer() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
    isTimerRunning = true

}
@IBAction func resetButtonTapped(_ sender: UIButton) {
    timer.invalidate()
    seconds = 60
    timerLabel.text = timeString(time: TimeInterval(seconds))
    isTimerRunning = false

}

//MARK: - Public Method
func updateTimer(){
    if seconds < 1 {
        timer.invalidate()
        //Send alert to indicate time's up.
    } else {
        seconds -= 1
        timerLabel.text = timeString(time: TimeInterval(seconds))
    }
}

func timeString(time:TimeInterval) -> String {
    let hours = Int(time) / 3600
    let minutes = Int(time) / 60 % 60
    let seconds = Int(time) % 60
    return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
    }}

Hmmm, before we start trying to chain timers maybe we could just use one and display it as though it were two, one after the other... 嗯,在我们开始尝试链接计时器之前,也许我们可以只使用一个并将其显示为两个,一个接一个地显示 ...

Now your first timer starts at 3, and the second at 60, 3 is less than 60... 现在您的第一个计时器从3开始,第二个计时器在60,3小于60 ...

Maybe we could start the timer at 64 but display the time as remainder(time, 61), those remainders would go 3, 2, 1, 0, 60, 59, ... 也许我们可以在64点启动计时器,但将时间显示为剩余时间(time,61),这些剩余时间将变为3、2、1、0、60、59,...

Remainder in Swift is % . Swift中剩余的是%

So something like: 所以像这样:

  • start the time at 64 时间开始于64
  • change the parameter name of timeString to actualTime , and timeString的参数名称timeStringactualTime ,然后
  • add let time = actualTime % 61 as its first line. let time = actualTime % 61添加为第一行。

BTW: The constant 60 occurs twice in your code, think about using a let constant for it and use that to reset variables. 顺便说一句:常数60在您的代码中出现两次,请考虑为其使用let常数,然后使用该常数重置变量。 Introduce a similar constant for the pre-countdown, etc. 为预倒数引入类似的常量,等等。

HTH HTH

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

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