Akshay Kankal Akshay Kankal - 1 month ago 21
Swift Question

Simple Timer in iOS

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

Answer

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
}