Свифт, как проверить, установлен ли таймер, используя время из определенной переменной? - PullRequest
0 голосов
/ 14 апреля 2020

Я работаю над приложением таймера, которое принимает две переменные как времена для таймера periodOneTime и periodTwoTime. Когда время на одном periodOneTime истекло, я хочу, чтобы мое приложение переключилось на periodTwoTime, и назад и вперед для моего таймера.

Переменная timeLeft под функцией secondTimer содержит эти переменные, чтобы проверить, работает ли таймер, и мне нужен способ проверить, истекло ли время на periodOneTime и periodTwoTime, чтобы я мог переключиться на следующий раз. Я понятия не имею, с чего начать. Спасибо за любую помощь!

  @IBAction func startTimer(_ sender: UIButton) {
    periodOneTime = Int(periodOne.text!)!
    periodTwoTime = Int(periodTwo.text!)!

    timeLeft = periodOneTime

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

@IBAction func stopTimer(_ sender: UIButton) {
    timer?.invalidate()
    timeRemaining.text = "0"
}

@objc func onTimerFires()
{
    timeLeft -= 1
    timeRemaining.text = String(timeLeft)

    if timeLeft <= 0 {
        timer?.invalidate()
        timer = nil
    }
    //checks if time left is 0, then stops and starts second timer from periodTwo
    if timeLeft == 0 {
        timer?.invalidate()
        secondTimer()
    }
}
//Function to switch to second timer (periodTwo)
func secondTimer(){

    if timeLeft < 1{
        timeLeft = periodTwoTime
          timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
        }

}

1 Ответ

0 голосов
/ 15 апреля 2020

Есть более простой способ сделать это, используя один таймер, который вы используете для обновления дисплея, и просто отслеживаете, бежите вы или гуляете - что-то вроде этого

@IBAction func cmdStartStopAction(_ sender: Any)
{
    durationTimerDisplay = 0.1 // this will update the display every 0.1 seconds
    currentlyRunning = true // assume we start by running

    if timerDisplay == nil // this means we are starting the timer
    {
        durationRun = Double(txtTimerRun.text!)!    // assumes you have a text box to enter the times
        durationWalk = Double(txtTimerWalk.text!)!

        durationRemaining = durationRun             // we can use this to display a countdown timer

        // start the display update timer
        timerDisplay = Timer.scheduledTimer(timeInterval: durationTimerDisplay, target: self, selector: #selector(onTimerDisplay), userInfo: nil, repeats: true)
    }
    else
    {
        timerDisplay.invalidate()
        timerDisplay = nil
    }
}

@objc func onTimerDisplay()
{
    durationRemaining -= durationTimerDisplay       // count down timer
    if durationRemaining <= 0                       // switch between running and walking when you reach zero
    {
        // switch from running to walking, or walking to running
        currentlyRunning = !currentlyRunning
        if currentlyRunning {
            durationRemaining = durationRun
        }
        else {
            durationRemaining = durationWalk
        }
    }

    // create a display using a label lblTimer
    if currentlyRunning {
        lblTimer.text = String(format: "RUN: %.1f", durationRemaining)
    }
    else {
        lblTimer.text = String(format: "WALK: %.1f", durationRemaining)
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...