我正在试图交出5张牌,一次一张,每张牌的交易稍有延迟。该卡是UIButtons,我正在将按钮图像更改为卡的图像。我的代码如下。我也尝试过使用NSTimer的解决方案但得到相同的结果。问题在于,无论延迟时间间隔是什么,都会发生延迟,但所有卡片都会立即出现。任何帮助,将不胜感激。谢谢。
var index = 0
for card in [card1, card2, card3, card4, card5] {
if canBeDealt(card) {
let oneCard = myDeck.deal1()
pokerHand[index] = oneCard
let cardPic = UIImage(named: "PNGCards/" + oneCard + ".png")!
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
card.setBackgroundImage(cardPic, forState: .Normal)
card.setTitle("", forState: .Normal)
}
}
index += 1
}
答案 0 :(得分:0)
问题是dispatch_after
是一个异步函数,所以它立即返回。您将在几毫秒后开始循环的新迭代,因此所有卡片似乎立即显示。您需要引入delay
变量:
var delay = 0.0
for card in [card1, card2, card3, card4, card5] {
if canBeDealt(card) {
// ...
delay += 0.5 * Double(NSEC_PER_SEC)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delay), dispatch_get_main_queue()) {
card.setBackgroundImage(cardPic, forState: .Normal)
card.setTitle("", forState: .Normal)
}
}
}