1

I made a stopwatch in swift. It has three buttons- play, stop, reset. it has a display in the middle where I display the seconds passed.

My code runs fine. But the watch runs very fast after the stop or reset.

I am not able to figure out what is the fuss.

please help!

var time = 0
var timer = NSTimer()
var pause = Bool(false)


@IBOutlet var result: UILabel!

func displayResult() {

    if pause != true
    {
        time++
        result.text = String(time)
    }
}
@IBAction func reset(sender: AnyObject) {

    time = 0

    result.text = String(time)

}


@IBAction func pause(sender: AnyObject) {

    pause = true

}



@IBAction func play(sender: AnyObject) {

    pause = false
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("displayResult") , userInfo: nil, repeats: true)
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
KawaiKx
  • 9,558
  • 19
  • 72
  • 111
  • do not use a timer to measure time. Get the start date and get that date timeIntervalSinceNow https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/#//apple_ref/occ/instp/NSDate/timeIntervalSinceNow – Leo Dabus Dec 30 '15 at 04:42
  • to display the time interval http://stackoverflow.com/a/30772571/2303865 – Leo Dabus Dec 30 '15 at 04:47

1 Answers1

1

Your pause action should be:

@IBAction func pause(sender: AnyObject) {

    timer.invalidate()
    pause = true

}

UPD:

var time = 0
var timer = NSTimer()
var pause = true // 1

func displayResult() {

    if pause != true
    {
        time++
        label.text = String(time)
    }
}
@IBAction func reset(sender: AnyObject) {

    time = 0

    label.text = String(time)
    timer.invalidate() // 2
    pause = true // 3
}


@IBAction func pause(sender: AnyObject) {
    timer.invalidate() // 4
    pause = true

}

@IBAction func play(sender: AnyObject) {

    // 5
    if pause == true {
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("displayResult") , userInfo: nil, repeats: true)
        pause = false
    }
}
aaisataev
  • 1,643
  • 3
  • 22
  • 38