簡體   English   中英

迅速:將倒數計時器停止為零

[英]swift: stop countdown timer at zero

我是Swift的新手-嘗試為iPhone / iPad構建應用程序。 希望您能夠幫助我。

我想包括一個從04:00分鍾到00:00倒數的計時器。 然后,它應該在零處停止並觸發聲音效果(我尚未嘗試實現)。 當您按下開始按鈕時,倒數開始(在我的代碼中startTimer和stopTimer指的是同一按鈕;但是,按鈕在開始時僅被按下一次)。

計時器啟動並倒計時就好了。 它將按計划將秒轉換為分鍾。 但是,我的主要問題是我無法倒數到零。 它持續到00:0-1等。我該如何解決?

import Foundation
import UIKit
import AVFoundation


class Finale : UIViewController {



    @IBOutlet weak var timerLabel: UILabel!


    var timer = NSTimer()
    var count = 240
    var timerRunning = false




    override func viewDidLoad() {
        super.viewDidLoad()

    }



    func updateTime() {
        count--


        let seconds = count % 60
        let minutes = (count / 60) % 60
        let hours = count / 3600
        let strHours = hours > 9 ? String(hours) : "0" + String(hours)
        let strMinutes = minutes > 9 ? String(minutes) : "0" + String(minutes)
        let strSeconds = seconds > 9 ? String(seconds) : "0" + String(seconds)
        if hours > 0 {
            timerLabel.text = "\(strHours):\(strMinutes):\(strSeconds)"
        }

        else {
            timerLabel.text = "\(strMinutes):\(strSeconds)"
        }

    }



    @IBAction func startTimer(sender: AnyObject) {

        var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)

    }

 func stopTimer() {

    if count == 0 {
        timer.invalidate()
        timerRunning = false
           }
    }



    @IBAction func stopTimer(sender: AnyObject) {
        timerRunning = false
     if count == 0 {
    timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("stopTimer"), userInfo: nil, repeats: true)
        timerRunning = true
        }}

}
func updateTime() {
        count--


        let seconds = count % 60
        let minutes = (count / 60) % 60
        let hours = count / 3600
        let strHours = hours > 9 ? String(hours) : "0" + String(hours)
        let strMinutes = minutes > 9 ? String(minutes) : "0" + String(minutes)
        let strSeconds = seconds > 9 ? String(seconds) : "0" + String(seconds)
        if hours > 0 {
            timerLabel.text = "\(strHours):\(strMinutes):\(strSeconds)"
        }

        else {
            timerLabel.text = "\(strMinutes):\(strSeconds)"
        }
    stopTimer()
}

請記住,您的計時器不會倒數至零-您可以在代碼中實現該計時器。 計時器每秒觸發一次。

在您的updateTime函數中,您需要使定時器無效,並在定時器用盡時調用聲音函數

好極了! 工作正常! 我混合使用了兩個答案。 我在我的updateTimer函數中添加了stopTimer(),從計時器中刪除了“ var”,並刪除了代碼的最后一段/ IBAction。 十分感謝大家! 現在,我將嘗試添加聲音。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM