2

So I am making a guessing app and I am wondering how can I make a string change or label after one second.

For an example, when the user presses the button it will say Yes or No. After it displays Yes or No it will then wait one second and go back to ????. How will I go about adding a timer so after it displays Yes it will go back to ???? in one second?

Thanks

rmaddy
  • 314,917
  • 42
  • 532
  • 579
winter4w
  • 57
  • 6

2 Answers2

6
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
    // change label here
}
T. Benjamin Larsen
  • 6,373
  • 4
  • 22
  • 32
  • Sweet it worked, however, how would I make it so the timer resets every time the button is pushed. The issue I am haveing now is, when they press the button it will change the label and the timer will clock one second and change it back to default however if they click the button before that second hits the label will still change within a half a second after the second click and then change again due to the second click. If any of that makes sense lol – winter4w Jan 28 '17 at 01:07
  • Kind of sounds like a different question, but it would be as easy as setting the `button.isUserInteractionEnabled = false` when tapped. Then set it back to `true` at the same time as you change the label back... – T. Benjamin Larsen Jan 28 '17 at 11:52
0

First Set up a timer :

override func viewWillAppear() {
super.viewWillAppear(animated)
_ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: false)    
}

Function which gets called when timer hits one second. Note this timer would run only once.

func runTimedCode() {
//Change your string here
}

Welcome to SO. Hope it helps. Comment down if you run into any error. Happy Coding.

Md. Ibrahim Hassan
  • 5,359
  • 1
  • 25
  • 45