如何延迟 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!")
}

最新更新