秒表代码问题

时间:2016-06-19 00:52:51

标签: swift

我正在尝试创建一个秒表应用程序,出于某种原因,当我按下应用程序中的开始按钮而不是它,1,2,3,4,5等。它显示了这个'<'。我已经查了代码,但我找不到任何东西。

class ViewController: UIViewController {

    var timer = NSTimer()

    var time = 0

    func result() {
        time + 1
        timeLabel.text = "\(timer)"
    }

    @IBOutlet var timeLabel: UILabel!

    @IBAction func stop(sender: AnyObject) {
        timer.invalidate()

        time = 0
        timeLabel.text = "0"
    }

    @IBAction func timeButton(sender: AnyObject) {
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
    }

}

1 个答案:

答案 0 :(得分:0)

您有错字:timeLabel.text = "\(timer)"应为timeLabel.text = "\(time)"

此外,time + 1应为time += 1。通过这些更改,以下代码可以正常运行:

class ViewController: UIViewController {

    var timer = NSTimer()

    var time = 0

    func result() {
        time += 1
        timeLabel.text = "\(time)"
    }

    @IBOutlet var timeLabel: UILabel!

    @IBAction func stop(sender: AnyObject) {
        timer.invalidate()

        time = 0
        timeLabel.text = "0"
    }

    @IBAction func timeButton(sender: AnyObject) {
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(result), userInfo: nil, repeats: true)
    }

}