繁体   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