Simple Timer in iOS

时间:2016-10-20 12:43:02

标签: ios swift timer

I'm trying to make a simple timer in iOS using Swift. The program is working fine but whenever my START UIButton is pressed the function of timer starts and runs multiple time as much as the button is pressed.

I want to disable the START UIButton as soon as the timer function starts so that it does not run multiple times.

Please help me for the same.

This is my code of ViewController

import UIKit

class ViewController: UIViewController {
    var time = 0.0
    var timer = Timer()

    @IBOutlet weak var lbl: UILabel!

    @IBAction func start(_ sender: UIButton)
    {
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
    }

    @IBAction func pause(_ sender: UIButton)
    {
        timer.invalidate()
    }

    @IBAction func reset(_ sender: UIButton)
    {
        timer.invalidate()
        time = 0.0
        lbl.text = ("0")
    }

    func action()
    {
        time += 0.1
        lbl.text = String(time)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

2 个答案:

答案 0 :(得分:3)

To disable your button you can just set it's isUserInteractionEnabled property in start function:

@IBOutlet weak var startButton: UIButton!

@IBAction func start(_ sender: UIButton) {
    timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
    startButton.isEnabled = false
}

Then set it back to true in pause and reset methods:

@IBAction func pause(_ sender: UIButton) {
    timer.invalidate()
    startButton.isEnabled = true
}

@IBAction func reset(_ sender: UIButton) {
    timer.invalidate()
    startButton.isEnabled = true 
    //the rest of your code
}

答案 1 :(得分:2)

The most reliable way to ensure that the timer is only started and stopped once is writing two methods which check the current state (timer is not nil if it's currently running):

var timer : Timer?

func startTimer()
{
  guard timer == nil else { return }
  timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
  // disable start button
}

func stopTimer()
{
  guard timer != nil else { return }
  timer!.invalidate()
  timer = nil
  // enable start button
}

In the methods you can enable/disable the button(s) accordingly.