如何编写Swift 3中的延迟

本文翻译自:How to program a delay in Swift 3

In earlier versions of Swift, one could create a delay with the following code: 在早期版本的Swift中,可以使用以下代码创建延迟:

let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
    //put your code which should be executed with a delay here
}

But now, in Swift 3, Xcode automatically changes 6 different things but then the following error appears: "Cannot convert DispatchTime.now to expected value dispatch_time_t aka UInt64 ." 但是现在,在Swift 3中,Xcode会自动更改6个不同的内容,但随后出现以下错误:“无法将DispatchTime.now转换为期望值dispatch_time_t又名UInt64 。”

How can one create a delay before running a sequence of code in Swift 3? 如何在Swift 3中运行一系列代码之前创建延迟?


#1楼

参考:https://stackoom.com/question/2zzDr/如何编写Swift-中的延迟


#2楼

After a lot of research, I finally figured this one out. 经过大量的研究,我终于想到了这个。

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
   // Code you want to be delayed
}

This creates the desired "wait" effect in Swift 3 and Swift 4. 这在Swift 3和Swift 4中创建了所需的“等待”效果。

Inspired by a part of this answer . 灵感来自这个答案的一部分。


#3楼

Try the following function implemented in Swift 3.0 and above 尝试在Swift 3.0及更高版本中实现的以下功能

func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { 
        completion()
    }
}

Usage 用法

delayWithSeconds(1) {
   //Do something
}

#4楼

I like one-line notation for GCD, it's more elegant: 我喜欢GCD的单行表示法,它更优雅:

    DispatchQueue.main.asyncAfter(deadline: .now() + 42.0) {
        // do stuff 42 seconds later
    }

Also, in iOS 10 we have new Timer methods, eg block initializer: 此外,在iOS 10中我们有新的Timer方法,例如块初始化器:

(so delayed action may be cancelled) (因此可能会取消延迟行动)

    let timer = Timer.scheduledTimer(withTimeInterval: 42.0, repeats: false) { (timer) in
        // do stuff 42 seconds later
    }

Btw, keep in mind: by default, timer is added to the default run loop mode. 顺便说一句,请记住:默认情况下,计时器被添加到默认的运行循环模式。 It means timer may be frozen when this loop mode is on hold (for example, when scrolling a UIScrollView) You can solve this issue by adding the timer to the specific run loop mode: 这意味着当此循环模式处于保持状态时(例如,滚动UIScrollView时)可能会冻结计时器。您可以通过将计时器添加到特定的运行循环模式来解决此问题:

RunLoop.current.add(timer, forMode: .commonModes)

At this blog post you can find more details. 在这篇博文中,您可以找到更多详细信息。


#5楼

//Runs function after x seconds //在x秒后运行功能

public static func runThisAfterDelay(seconds: Double, after: @escaping () -> Void) {
    runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}

public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> Void) {
    let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
    queue.asyncAfter(deadline: time, execute: after)
}

//Use:- //使用:-

runThisAfterDelay(seconds: x){
  //write your code here
}

#6楼

Try the below code for delay 请尝试以下代码进行延迟

//MARK: First Way

func delayForWork() {
    delay(3.0) {
        print("delay for 3.0 second")
    }
}

delayForWork()

// MARK: Second Way

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    // your code here delayed by 0.5 seconds
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值