Xcode (Swift) 中的等待/延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32316614/
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:44:53  来源:igfitidea点击:

Wait/Delay in Xcode (Swift)

xcodeswiftdelay

提问by ChubbyChocolate

How do i add a delay in Xcode?

如何在 Xcode 中添加延迟?

self.label1.alpha = 1.0
//delay
self.label1.alpha = 0.0

I'd like to make it wait about 2 seconds. I've read about time_dispatch and importing the darwin library, but i haven't been able to make it work. So can someone please explain it properly step by step?

我想让它等待大约 2 秒钟。我已经阅读了有关 time_dispatch 和导入 darwin 库的信息,但我一直无法使其正常工作。那么有人可以一步一步地解释一下吗?

回答by Adagio

You only have to write this code:

您只需要编写以下代码:

self.label1.alpha = 1.0    

let delay = 2 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
    // After 2 seconds this line will be executed            
    self.label1.alpha = 0.0
}

'2' is the seconds you want to wait

'2' 是你想要等待的秒数

Regards

问候

回答by BK15

This is another option that works -

这是另一个有效的选择 -

import Darwin sleep(2)

import Darwin sleep(2)

Then, you can use the sleep function, which takes a number of seconds as a parameter.

然后,您可以使用 sleep 函数,该函数以秒数作为参数。

回答by Choppin Broccoli

Might be better to use blocks for this one:

对这个使用块可能会更好:

self.label1.alpha = 1.0;

UIView animateWithDuration:2.0 animations:^(void) {
    self.label1.alpha = 0.0;
}];

回答by FireFliesVA

For Swift 5:

对于 Swift 5:

self.label1.alpha = 1.0 

let delay : Double = 2.0 //delay time in seconds
let time = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline:time){
    // After 2 seconds this line will be executed
    self.label1.alpha = 0.0
}

This works for me.

这对我有用。

Referring to: Delay using DispatchTime.now() + float?

参考:Delay using DispatchTime.now() + float?