Search code examples
loopsswiftuitimer

On Xcode, How do I increase the variable 'counter' by 1 every second as long as the screen is held?


I've recently started learning and playing around with Xcode but I've been having some issues.

I need a variable speed to increase by 1 every second I hold the screen. I read the docs but I barely understood anything and a lot of the info looks irrelevant for what I'm doing. Here's the code I have right now:

class ViewController: UIViewController {\
    @IBOutlet weak var counterLabel: UILabel!
    var counter = 0
    // The number of seconds after which to update
    var speed = 1

    override func viewDidLoad() {
        super.viewDidLoad()
        counterLabel.text = "\(counter)"
    }

    @IBAction func screenHeld(_ sender: Any) {
        // Need to add code here
    }
}

Solution

    • Create a global Timer variable. When the user touches the screen, the timer is started.
    • The Timer will increment your global variable. Also check if your condition is met in the timer callback.
    • When the user releases the finger from the screen, the timer is invalidated and the global variable is reset to zero.

    Here is come untested code to get you started:

    var timer: Timer?
    var myCounter = 0
    
    // Connect to the corresponding control or the tap recognizer.
    @IBAction func screenBeginTouch(_ sender: Any)
    {
        self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true)
        {
            timer in
            self.myCounter += 1
            // Check condition here
        }
    }
    
    // Connect to the corresponding control or the tap recognizer.
    @IBAction func screenEndTouch(_ sender: Any)
    {        
        self.timer?.invalidate()
        self.timer = nil
        self.myCounter = 0
    }
    

    Timer Apple Documentation