我只是在学习 iOS 和一般编程,我正在制作一个非常基本的 iOS 秒表应用程序。然而,我让秒表工作了,当我多次按下开始时,计时器开始走得更快,以至于它不再是一秒钟长(gif here)。另外,我的格式似乎在第二部分不正确,如果您有任何建议,我们将不胜感激。这是我的代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var minuteLabel: UILabel!
@IBOutlet weak var secondLabel: UILabel!
var timer = NSTimer()
var second = 0
var minute = 0
func updateTime() {
do{
if second != 59
{
second++
secondLabel.text = ".\(second)"
}
else
{
second = 0
minute++
secondLabel.text = "." + String(format:"$%.2f", second)
if minute < 10
{
minuteLabel.text = "0\(minute)"
}
else
{
minuteLabel.text = String(format:"$%.2f", minute)
}
}
}
}
@IBAction func resetButton(sender: AnyObject) {
timer.invalidate()
second = 0
minute = 0
secondLabel.text = ".00"
minuteLabel.text = "00"
}
@IBAction func stopButton(sender: AnyObject) {
timer.invalidate()
}
@IBAction func startButton(sender: AnyObject) {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
}
感谢您的帮助!
最佳答案
调用 startButton
时,您并未使 timer
无效,因此多次点击“开始”会创建重复的计时器,这些计时器会调用相同的函数 updateTime
。将 startButton
更改为如下所示:
@IBAction func startButton(sender: AnyObject) {
if !timer.valid
{
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
}
}
对于关于格式的第二个问题,您需要设置一个条件来检查秒是否小于 10,类似于您对分钟所做的。你会在秒前放一个 0。在 更新时间
中:
if second < 10
{
second++
secondLabel.text = ".0\(second)"
}
else if second <= 59
{
second++
secondLabel.text = ".\(second)"
}
else
{
...
}
参见 NSTimer documentation获取更多信息。
关于ios - 秒表应用计数器走得太快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34366699/