簡體   English   中英

UILabel中的倒數計時器

[英]Countdown timer in UILabel

我創建了一個應用,一個倒數計時器,該計時器從xxx秒倒數到0。這很好用。

現在我想擁有一個計數器。

像這樣:

第一個計數器從15到0,然后第二個計數器從120到0。

這兩個計數器應使用相同的UILabel。

到目前為止,這是我所做的:

var timerCount = 10
var timerRunning = false
var timer = NSTimer()
var audioPlayer:AVAudioPlayer?

// Code for the Sound - Start

func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer  {
    let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
    let url = NSURL.fileURLWithPath(path!)

    do {
        try audioPlayer = AVAudioPlayer(contentsOfURL: url)
    } catch {
        print("NO AUDIO PLAYER")
    }

    return audioPlayer!
}

// Code for Sound - End

// INFO LABEL
@IBOutlet weak var infoLabel: UILabel!
// INFO LABEL END

weak var timerLabel: UILabel!

func Counting(){

    timerCount -= 1
    timerLabel.text = "\(timerCount)"
    if timerCount == 0{
        timer.invalidate()
        timerRunning = false
        timerCount = 10
        timerLabel.text = "0"
        timerLabel.backgroundColor = UIColor.redColor()

    }
    if timerCount == 5{

        let backMusic = setupAudioPlayerWithFile("start", type: "wav")
        backMusic.play()

        timerLabel.backgroundColor = UIColor.yellowColor()

    }
    if timerCount == 10{
        timerLabel.backgroundColor = UIColor.redColor()
        timer.invalidate()
        timerRunning = false
        infoLabel.text = "Timer stopped"
    }

}

@IBAction func startButton(sender: UIButton) {

    let backMusic = setupAudioPlayerWithFile("start", type: "wav")
    backMusic.play()


    if timerRunning == false{

    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("Counting"), userInfo: nil, repeats: true)
       timerRunning = true
    }

    timerLabel.backgroundColor = UIColor.greenColor()
    infoLabel.text = "Timer started"

}

您可以使用GCD簡化操作:

func counting() {
    timeCount--
    timerLabel.text = "\(timerCount)"
    if timeCount == 0 {
        timerRunning = false
        timerLabel.backgroundColor = UIColor.redColor()
        infoLabel.text = "Timer stopped"
        return
    } else if timerCount == 5 {
        let backMusic = setupAudioPlayerWithFile("start", type: "wav")
        backMusic.play()
        timerLabel.backgroundColor = UIColor.yellowColor()
    }
    startNextCount()
}

func startNextCount() {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), self.counting)
}

@IBAction func startButton(sender: UIButton) {
    if timerCount > 0 {
        return
    }
    timerCount = 10
    let backMusic = setupAudioPlayerWithFile("start", type: "wav")
    backMusic.play()
    timerLabel.backgroundColor = UIColor.greenColor()
    infoLabel.text = "Timer started"
    startNextCount()
}

暫無
暫無

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

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