Search code examples
swifttimeruikituibutton

Call a timer function only when a UIButton is clicked


I have a function that I want to run every time an interval is called but I only want to execute once my UIButton is clicked. My problem is that since the moment I run my simulator, the function executes on its own. In order to prevent that from happening I tried to define a isPlayButtonClicked and initialize to false so when the playAnimation UIButton is clicked, it sets it to true and then a wasPlayButtonClicked that checks if the initial boolean value changes will print in the console "selected" but like I said, I see it printed even before I click my button.

 var setTimer: Timer!
 var isPlayButtonClicked: Bool = false

 @objc func playAnimation(_ sender: Any) {

         isPlayButtonClicked = true
        wasPlayButtonClicked()
    }

  func wasPlayButtonClicked() {
        if isPlayButtonClicked == true  {
            print("selected ")
        }
    }


    
    override func viewDidLoad() {
        super.viewDidLoad()

setTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(playAnimation(_:)), userInfo: nil, repeats: true)


}

How could I make it wait for my click event to execute?


Solution

  • The simplest fix is to change the timer so it calls the wasPlayButtonClicked selector instead of the playAnimation selector.

    A better fix is to trigger the timer in the playAnimation function. No need to start the timer until the button is actually tapped.

    Here's a rework of your view controller:

    class SomeVC: UIViewController {
        var setTimer: Timer? // change to optional
    
        @objc func playAnimation(_ sender: Any) {
            setTimer?.invalidate() // Esnure there's only one timer even if the button is tapped multiple times
            // Change selector to wasPlayButtonClicked
            setTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(wasPlayButtonClicked), userInfo: nil, repeats: true)
    
            wasPlayButtonClicked()
        }
    
        @objc func wasPlayButtonClicked() {
            print("selected")
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Don't setup the timer here
        }
    }
    

    Note that you'll probably want to invalidate the timer when the view controller is dismissed.