Search code examples
swiftbuttonwhile-looptimer

Run Counter while button press


I am very new to swift and I want to make a button work like this: Press the Button and hold. While the Button is pressed the label value goes up like every second +1 until the button is released.

This is what I get so far:

    class ViewController: UIViewController {
        var counter = 0;
        override func viewDidLoad() {
            super.viewDidLoad();

        }

        @IBOutlet weak var label: UILabel!

        @IBAction func btn(_ sender: Any) {
            if (sender as AnyObject).state != .ended{
                counter+=1;
                // wait 100ms
                self.label.text = String (counter);
            }
        }
    }

This is how I linked it:


Solution

  • You can achieve this using the UIButton actions Touch Down and Touch Up Inside

    class ViewController: UIViewController {
    
    
    var timer : Timer?
    var startTime = 0 
    var timerReset = true // I don't know what logic you want. This basically has been added so the number is not set to 0 immediately when you release the button. You can also add another button to reset startTime variable and the label
    
    @IBOutlet weak var numberLabel: UILabel!
    @IBOutlet weak var numberButton: UIButton!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        numberLabel.text = String(startTime) //initial value
        // Do any additional setup after loading the view.
    }
    
    @IBAction func holdingTheButton(_ sender: Any) {
        print("I am holding")
        timerReset = false // reset to false since you are holding the button
        guard timer == nil else { return }
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
    }
    
    @IBAction func buttonReleased(_ sender: Any) {
        print("button released")
        startTime = 0
        timer?.invalidate()
        timer = nil
        timerReset = true // reset to true since you released. 
    }
    
    @objc func updateTime(){
        //update label every second
        print("updating label ")
        if timerReset {
            startTime = 0
        }
        startTime += 1
        numberLabel.text = String(startTime)
    } 
    }
    

    IMPORTANT: Make sure you are connecting in the right way. Touch Down has to be used if you want to call the function while you hold the button:

    enter image description here

    In your console, you should see this happening if you release the button after 10 SECONDS:

    enter image description here

    If you want to have a button to reset, you can just add the it and then connect it to the following function (but also make sure you remove the bool timeReset and the if statement inside updateTime:

    @IBAction func resetTimer(_ sender: Any) {
      startTime = 0
      numberLabel.text = String(startTime)
    }