2015-10-05 42 views
0

我创建了一个应用程序,一个倒数计时器,它从xxx秒向下计数到0. 这很好。UILabel中的倒数计时器

现在我想要一个优先考虑。

像这样:

从15至0℃,然后我的第二计数器120为0。

这些2个计数器首先计数器应使用相同的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

对不起....确切的问题是,我不知道如何实现我的预处理器。我试图在startButton中复制和粘贴第二个函数,但它没有生效 – Roland

+0

我的答案成功了吗? – mixel

回答

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() 
} 
+0

ty ...我会尝试一下并给出回应:-) – Roland