如何推迟在Swift中发生的事情?

时间:2015-01-28 12:41:33

标签: 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 - 计时器标签

1 个答案:

答案 0 :(得分:9)

您可以使用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!")
}