我需要构建一个 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/