我是Swift的新手 - 尝试为iPhone / iPad构建应用程序。希望您能够帮助我。
我想要包括一个从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 :(得分: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()
}
答案 1 :(得分:1)
请记住,您的计时器不会倒数到零 - 您在代码中实现了这一点。计时器每秒都会触发。
在你的updateTime函数中,你需要使计时器无效,并在计时器用完时调用你的声音函数
答案 2 :(得分:0)
耶!它的工作!!我使用了两个答案的混合。我将stopTimer()添加到我的updateTimer函数中,我从计时器中删除了“var”,并删除了我的代码的最后一段/ IBAction。十分感谢大家!现在我会尝试添加声音。 :)