user8105388
user8105388

Reputation:

if statement depending on timer

My code below is trying to stop the timer when it reaches 2 seconds. Thats what I have now is not working and I don't know what else to do. I thought viewdidappear would work. I think counter is the what I should make the if statement around.

import UIKit
class ViewController: UIViewController {
@IBOutlet var playbutton: UIButton!
@IBOutlet var titlelabel: UILabel!

var timer = Timer()
var counter = 0.0
var isRunning = false


override func viewDidLoad() {
    super.viewDidLoad()
    titlelabel.text = "\(counter)"
    playbutton.isEnabled = true

}
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if counter == 1.9 {
            timer.invalidate()
        }
    }

@IBAction func btnreset(_ sender: UIButton) {
    timer.invalidate()
    titlelabel.text = "\(counter)"
    counter = 0
    playbutton.isEnabled = true

    isRunning = false
}
@IBAction func btnplay(_ sender: UIButton) {
    if !isRunning{
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(UpdateTime), userInfo: nil, repeats: true)
        playbutton.isEnabled = false
    isRunning = true
    }

}
@objc func UpdateTime(){
    counter += 0.1
    titlelabel.text = String(format: "%.1f", counter)

}}

Upvotes: 0

Views: 41

Answers (1)

vadian
vadian

Reputation: 285092

There are a few issues.

  • Declare the timer as optional, then you can remove the isRunning variable, the timer is running if it's not nil

    var timer : Timer?
    
    ...
    
    @IBAction func btnplay(_ sender: UIButton) {
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
            playbutton.isEnabled = false
        }
    }
    
  • The check if the timer exceeds 2 seconds must be performed in the updateTime function, because it's called frequently. viewDidAppear is only called once.

  • A check == 1.9 does not work reliably because a floating point value is not exactly 1.9.
    Check for is equal or greater than

    @objc func updateTime()
    {
        counter += 0.1
        titlelabel.text = String(format: "%.1f", counter)
        if counter >= 1.9 {
            timer?.invalidate()
            timer = nil
        }
    }
    
  • In btnreset check if the timer is running and reset it to nil

    @IBAction func btnreset(_ sender: UIButton) {
        if timer != nil {
            timer!.invalidate()
            timer = nil
            titlelabel.text = "\(counter)"
            counter = 0
            playbutton.isEnabled = true
        }
    }
    

Upvotes: 1

Related Questions