Search code examples
iosif-statementtimerswift4

If statement not working with timer


When 10 seconds hit the timer. I would like the background color to be change. Right now my code is not working. Nothing is being changed when the code hits 10 seconds. I also dont think the timer is working.

@IBOutlet var espn: UILabel!

var TIMER = Timer()
var seconds = 0


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)




    if seconds == 10{self.view.backgroundColor = UIColor.red
    }

}
@IBAction func startTimer() {       

        TIMER = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(threeVC.clocker), userInfo: nil, repeats: true)


}


@objc func clocker() {
    seconds += 1
    espn.text = String( seconds)   
    }
}

Solution

  • Try this code:

    @IBOutlet var espn: UILabel!
    
    var TIMER = Timer()
    var seconds = 0
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)        
    }
    
    @IBAction func startTimer() {
    
        TIMER = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(threeVC.clocker), userInfo: nil, repeats: true)
    
    
    }
    
    
    @objc func clocker() {
        seconds += 1
        espn.text = String( seconds)
        if seconds == 10{
            self.view.backgroundColor = UIColor.red
            print("soda")
        }
    }
    

    if statement should be written in @objc func clocker() not in viewDidAppear