For 循环 Swift 中的延迟 [英] Delay in For Loop Swift
本文介绍了For 循环 Swift 中的延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在 SwiftUI 中创建一个简单的纸牌游戏 (Set).我有一个按钮,点击时会发出 X 张新牌.目前,它使所有卡片一次显示.我想知道如何让它们一次一个出来.
I am creating a simple card game (Set) in SwiftUI. I have a button that will deal X new cards when tapped. Currently, it makes all cards show up at once. I was wondering how I could make them come out one at a time.
Deal 通过将一张新卡附加到模型中的 Deck 数组来工作.ContentView 在网格中显示每张卡片.
Deal works by appending a new card to a Deck array in the model. ContentView displays each card in the grid.
这是我目前在网上查找后所拥有的.显示第一张卡片,然后显示所有卡片
This is what I currently have after looking online. Displays first card then next all at once
func deal(_ numberOfCards: Int) {
withAnimation(Animation.easeInOut(duration: 1)) {
viewModel.deal()
}
for _ in 1..<numberOfCards {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) {
withAnimation(.easeInOut) {
viewModel.deal()
}
}
}
}
推荐答案
试试这个
func deal(_ numberOfCards: Int) {
withAnimation(Animation.easeInOut(duration: 1)) {
viewModel.deal()
}
for i in 1..<numberOfCards {
DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) * 0.7) {
withAnimation(.easeInOut) {
viewModel.deal()
}
}
}
}
这篇关于For 循环 Swift 中的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文