2016-01-12 117 views
0

我是Swift的新手 - 尝试为iPhone/iPad构建应用程序。希望您能够帮助我。swift:停止倒数计时器为零

我想包括一个从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 
     }} 

} 
+0

http://stackoverflow.com/a/29583418/2303865 –

回答

1

记住,你的定时器不倒数至零 - 您实现您的代码。计时器每秒都会触发。

在你的录入功能,你需要无效计时器,并调用你的声音功能,当计时器运行过程

+0

谢谢,罗素。我如何使其无效?我现在尝试添加如果计数== 0 { timer.invalidate() timerRunning = false } updateTime函数,但它不停止。 – mojomo

+0

这应该这样做 - 但你有两个版本的计时器!您有一个用类范围定义的变量,但您使用的变量仅在启动函数中定义。在初始化计时器之前,您需要删除'var',以便仅使用一个变量 – Russell

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

耶!它的工作!我用了两个答案的组合。我在我的updateTimer函数中添加了stopTimer(),我从计时器中删除了“var”,并删除了我的代码的最后一段/ IBAction。十分感谢大家!现在我会尝试添加声音。 :)

+0

酷 - 记得标记帮助您的答案:-) – Russell