ios - 秒表应用计数器走得太快

标签 ios swift

我只是在学习 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/

相关文章:

iphone - 如何在实现 UIGestureRecognizer 后删除手势

ios - 重新加载后 uicollectionviewcell 标签未对齐

ios - UIViewController 默认过渡动画不起作用

macos - 使用 Swift 和 Cocoa 创建 nswindow 的正确方法

ios - Swift:打印出 UILabel.text 时出现问题

swift - 在 IOS 10.0 或更高版本上本地化 Emoji 的阅读

ios - 在 Storyboard 中,有没有办法从布局中删除隐藏的项目?

ios - tableView 中的 insertSections

ios - 在 iOS 上从网页下载 CSV 文件

ios - 归档时应用程序获取 "Undefined symbols for architecture armv7",除非我不在库中删除链接产品