Search code examples
iosiphoneswiftstopwatch

Simple swift Stopwatch don't work


This is my code.

//
    //  ViewController.swift
    //  Stopwatch
    //
    //  Created by Orkun Atasoy on 12.09.15.
    //  Copyright (c) 2015 Orkun Atasoy. All rights reserved.
    //


import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var timerLabel: UILabel!
    @IBOutlet weak var timerButton: UIButton!

    var timer : NSTimer?
    var ms = 0

    @IBAction func buttonTapped(sender: AnyObject) {

        timerButton.setTitle("Stopp", forState:UIControlState.Normal)

        self.timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
    }


    func update() {
        self.ms++
        timerLabel.text = String(self.ms)enter code here
    }



}

The Problem is when i run the build it comes the introscreen with big text "Stopwatch" and the it is like freezed there. But it should come a label with button downside which has a text "start". When i click the button it should start counting and the label should change to "stopp". When i click again the it should stop the timer.

I dont get what the Problem ist. I am a Swift newbie. I would be pleased if you could help me.

Thank you for your attention

EDIT >> the label text is at the beginning "00:00".


Solution

  • Looks like you are messing with IBOutlet connections and I have corrected some of your code and here is working code:

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var timerLabel: UILabel!
        @IBOutlet weak var timerButton: UIButton!
    
        var timer : NSTimer?
        var ms = 0
    
        override func viewDidLoad() {
    
            timerLabel.text = "00:00"
        }
    
        @IBAction func buttonTapped(sender: AnyObject) {
    
            if timerButton.currentTitle == "Stopp" {
                timer?.invalidate()
                timerButton.setTitle("Start", forState:UIControlState.Normal)
            } else {
    
                timerButton.setTitle("Stopp", forState:UIControlState.Normal)
    
                self.timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
            }
        }
    
        func update() {
            self.ms++
            timerLabel.text = String(self.ms)
    
        }
    }
    

    And First of all remove all outlets from your storyboard view controller and connect it this way:

    enter image description here

    And if you want check THIS sample project.