Xcode Swift Ios app: adding delay

I am working on a simple quiz game and I want to add some slight delays to the game, now when I select an answer, the game immediately goes to the next answer, now I want to change the button color by 0.1 seconds and then load the next question

I tried the sleep function, but only adds a delay without changing the color, and I cannot select time intervals of less than a second, because it takes integers as a value

here is the code

sender.backgroundColor = UIColor.greenColor() sleep(1) sender.backgroundColor = UIColor.whiteColor() 

What should I put instead of sleep to get what I want?

thanks

+6
source share
4 answers

You can use NSTimer for this, firstly, you implement NSTimer and add a duration of 1.0 second or whatever you want, pass NSTimer time to its function call and you change questions to another

+1
source

If you only need the sleep function, just use

 NSThread.sleepForTimeInterval(1) 
+4
source

Use usleep , which takes an int in microseconds. (i.e., 1,000,000 microseconds is equivalent to 1 second). Thus, for 0.1 s use:

  // Sleep for 0.1s usleep(100000) 

Recommend use in background thread. You certainly do not want to do this on the main theme of the user interface!

+2
source

I think you should try NSTimer or dispatch_after to do things like this: (NSTimer may not be as convenient as it needs a class method used as a callback selector)

 sender.backgroundColor = UIColor.greenColor() dispatch_after(#your time#, dispatch_get_main_queue()){ sender.backgroundColor = UIColor.whiteColor() #load your new question logic# } 

PS: PerformSelector: delay: process is not available in Swift.

0
source

Source: https://habr.com/ru/post/985503/


All Articles