我只是在学习iOS和编程,我正在制作一个非常基本的iOS秒表应用程序.我让秒表正常工作,当我按下启动不止一次时,计时器开始变得更快,这样它就不再是第二长(这里是gif).此外,我的格式似乎是关闭秒部分,如果你有任何建议,将不胜感激.这是我的代码:
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) }
谢谢您的帮助!
调用timer
时不会失效startButton
,因此多次点击"开始"会创建调用相同函数的重复计时器,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.在updateTime
:
if second < 10 { second++ secondLabel.text = ".0\(second)" } else if second <= 59 { second++ secondLabel.text = ".\(second)" } else { ... }
有关更多信息,请参阅NSTimer文档.