[英]How to use sleep in swift 2.2
當我使用sleep(1)時,我的應用程序會在整個循環中休眠,而不是1秒。 90秒后 標簽得到更新,而不是每秒。
碼:
while time < 90 {
let goal = Int(arc4random_uniform(MAX) + MIN)
if goal < 5 {
scoreA = scoreA + 1
} else if goal > 15 {
scoreB = scoreB + 1
}
time = time + 1
scoreLabel.text = "\(scoreA) - \(scoreB)"
timeLabel.text = "\(time) min."
sleep(1)
}
我同意@arsen的答案,但我會盡力回答為什么會這樣。
您正在設置UILabel
文本,這表示您的代碼正在主線程上運行。 你在while循環的每個卷上調用sleep()
,在這種情況下,阻塞主線程90秒。 當主線程被阻止時,UI變得無法響應。
建議主線程上的代碼盡可能快地執行和退出,以便UI盡可能保持響應和流暢。
我認為NSTimer
更適合這種情況。
let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.