Use textfield to countdown to number swift4

My code below uses a label and a variable that contains 30 seconds. The code counts down to zero then stops. I want to do the same thing just use the var texty as the textfield for the user to enter a number and countdown from that amount of seconds.

   class twoViewController: UIViewController {
var TIMER = Timer()
var seconds = 30
let myL : UILabel = UILabel(frame: CGRect(x: 50, y: 50, width: 320, height: 50))
@IBOutlet var texty: UITextField!

      @IBAction func startTimer() {

    }
override func viewDidLoad() {
    super.viewDidLoad()


    myL.font = UIFont.init(name: "arial", size : 40 )
            myL.textColor = UIColor(red: 0xff, green: 0xff, blue: 0xff, alpha: 1)
    myL.textAlignment = .center
    myL.backgroundColor = UIColor(red: 0x00, green: 0x00, blue: 0x00, alpha: 0.2)
     self.view.addSubview(myL)
    TIMER = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(twoViewController.clocker), userInfo: nil, repeats: true)
}

@objc func clocker() {
    seconds = seconds - 1
    myL.text = String(seconds)
    if (seconds == 0) {
        TIMER.invalidate()
        myL.text = "Times UP"



    }
}

 }

hi @timswift,
You need to add a button that will trigger the timer using the text entered into the textbox.

If you use this in viewDidLoad, the user does not get a chance to select the duration.

cheers,

Jayant

Your right I added a button. What do I put in the button that starts the countdown to whatever is in the textfield.

Hi @timswift,
You add a button and in the code for when it is pressed, you start the timer.

 @IBAction func startTimer() {
  // This is the most important bit here...
  if let number = Int(texty.text) {
    seconds = number
    timer = Timer.ScheduledTimer(timeInterval: 1, target: self, ...)
  } else {
    // Display that the number in the text box is invalid or not a number
  }
 }

and it is a good habit to also nil the variable once you are done but that would mean using optionals (which you can skip for now).

cheers,

Jayant

I am having a problem with the undeclared used of timer var

Hi @timswift,
if you have copy pasted my code straight off, then you have to change my var timer to TIMER or as good variable naming conventions go, rename all of your instances of TIMER to timer

cheers,

Jayant

If I do that change var timer then I get the error message Type ‘Timer’ has no member ‘SchedulesTimer’.

hi @timswift,
It’s a typo at my end, my keyboard is playing up. it should be scheduled not schedules

and the … is so that I don’t have to type the entire line, please use what you had in that line.
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(twoViewController.clocker), userInfo: nil, repeats: true

cheers,

Jayant

This topic was automatically closed after 166 days. New replies are no longer allowed.