我创建了一个应用程序,倒数计时器,从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"
}
答案 0 :(得分:0)
使用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()
}