ios - 如何延迟 Swift 中发生的事情?

标签 ios swift

我需要构建一个 iOS Swift 单页应用程序,它有一个 60:00 分钟的倒计时器。 2 秒后我需要显示一个 UILabel,6 秒后将其隐藏,然后再显示另一个文本。到目前为止,这是我的计时器代码:

var startTime = NSTimeInterval()
var timer = NSTimer()

func startCountdownTimer() {

    var currentTime = NSDate.timeIntervalSinceReferenceDate()

    //Find the difference between current time and start time.
    var elapsedTime: NSTimeInterval = 3600-(currentTime-startTime)

    //Calculate the minutes in elapsed time.
    let minutes = UInt8(elapsedTime / 60.0)
    elapsedTime -= (NSTimeInterval(minutes) * 60)

    //Calculate the seconds in elapsed time.
    var seconds = UInt8(elapsedTime)
    elapsedTime -= NSTimeInterval(seconds)

    //Add the leading zero for minutes and seconds and store them as string constants
    let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
    let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)

    //Concatenate minutes and seconds and assign it to the UILabel
    timerLabel.text = "\(strMinutes):\(strSeconds)"

}

我试过这样做:

if elapsedTime == 2 {
    introTextLabel.hidden = false
}

或者这个:

if (elapsedTime: NSTimeInterval(seconds)) == 2 {
    introTextLabel.hidden = false
}

但它不起作用。 谁能帮忙?

introTextLabel - 显示文本的标签

timerLabel - 计时器标签

最佳答案

您可以使用由 matt 编写的这个有用的 delay() 函数.

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
    dispatch_get_main_queue(), closure)
}

用法:

// Wait two seconds:
delay(2.0) {
    print("Hello!")
}

关于ios - 如何延迟 Swift 中发生的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28192538/

相关文章:

ios - 将 firebase 操作放入哪个 GCD 队列? swift 4

iphone - "description"NSURLConnection 失败

ios - 未收到收据数据验证信息

iphone - NSRange 的多个 CTLine

ios - 未调用 iCarousel 数据源

ios - 更改权限时应用程序在后台崩溃 - swift

swift UITextView

ios - UITableViewCell 显示点击删除按钮

ios - 如何在 UITabBarController 中交换 ViewController

ios - 向 GMSMapView 添加手势识别器以获得 .begin/.ended/.change 手势