Xcode Swift Ios 应用程序:添加延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29743581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:02:09  来源:igfitidea点击:

Xcode Swift Ios App: Adding delay

iosxcodeswifttimerdelay

提问by GioB

I am working on a simple quiz game and i want to add some little delays to the game,now when i select the answer the game goes instantly to the next answer now i want to change the color of the button for 0.1 seconds and then loads the next question

我正在开发一个简单的问答游戏,我想为游戏添加一些延迟,现在当我选择答案时,游戏会立即转到下一个答案,现在我想更改按钮的颜色 0.1 秒,然后加载下一个问题

I tried the sleep function but it adds only the delay without the color change and i can't choose time intervals smaller than a second because it accepts integers as value

我尝试了睡眠功能,但它只增加了没有颜色变化的延迟,我不能选择小于一秒的时间间隔,因为它接受整数作为值

here is the code

这是代码

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

what i have to put instead of sleep to obtain what i want?

我必须放什么而不是睡觉才能获得我想要的东西?

thanks

谢谢

采纳答案by Y?lmaz Gürsoy

You can use NSTimerfor that, firstly you implement NSTimerand you add duration time 1.0 second or what ever want then, pass the time NSTimercall its function and you change questions to another

您可以使用NSTimer它,首先您实施NSTimer并添加持续时间 1.0 秒或任何想要的时间,然后传递时间NSTimer调用其函数,然后将问题更改为另一个

回答by Nerkyator

If you only need a sleep function, just use

如果您只需要睡眠功能,只需使用

NSThread.sleepForTimeInterval(1)

回答by TomV

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

使用以微秒为单位的 int 值的usleep。(即 1,000,000 微秒相当于 1 秒)所以对于 0.1s 使用:

       // Sleep for 0.1s
       usleep(100000) 

Recommend to use in a background thread. You certainly don't want to be doing this on the main UI Thread!

推荐在后台线程中使用。您当然不想在主 UI 线程上执行此操作!

回答by user3349433

I think you should try NSTimer or dispatch_after to do such things:(The NSTimer may be not so convenient as it needs a class method used as call back selector)

我认为您应该尝试使用 NSTimer 或 dispatch_after 来做这样的事情:(NSTimer 可能不太方便,因为它需要一个用作回调选择器的类方法)

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

P.S.:The performSelector:delay: method is not available in Swift.

PS:PerformSelector:delay: 方法在 Swift 中不可用。