我试图延迟不到一秒钟。我从网上找到了这段代码。然而,它不接受不到一秒的延迟。 Swift中的Grand Dispatch Concept对我来说有点神秘。我应该如何修改此代码以创建0.3秒的延迟?
let deadlineTime = DispatchTime.now() + .seconds(1) //how to get 0.3 seconds here
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
//code here
}
答案 0 :(得分:5)
嗯,这很简单,不用秒,使用毫秒:
let deadlineTime = DispatchTime.now() + .milliseconds(300) // 0.3 seconds
答案 1 :(得分:1)
只需将您需要的时间添加到DispatchTime.now()
,您就会得到一个结果
let deadlineTime = DispatchTime.now() + 0.3 //Here is 0.3 second as per your requirement
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
//code here
}
答案 2 :(得分:0)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
// your method after delay
}
请记住,这将在主线程上执行。如果您不想要,请选中DispatchQueue.global(qos:)
或this reference
答案 3 :(得分:-1)
使用它,将起作用
let delay = 2.5 * Double(NSEC_PER_SEC)
let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time, execute: {
self.view_Alert.alpha = 0
})