Ploostic Ploostic - 5 months ago 15
Swift Question

Stopwatch code Issue

I am trying to create a stopwatch app, for some reason when I press the start button in the app, instead of it going, 1,2,3,4,5 etc. It shows this '<'. I have gone over the code but I can find nothing.

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)
}

}

Answer

You have a typo: timeLabel.text = "\(timer)" should be timeLabel.text = "\(time)".

Also, time + 1 should be time += 1. With those changes, the following code works:

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)
    }

}
Comments