我在ZStack中有一副卡片组,我想一张张地向下移动纸牌.我正在努力实现这一点,当移动的卡片触底时,即将到来的卡片应该开始向下移动.我面临的问题是,整个ZStack正在向下移动,而不是一张卡.
import SwiftUI
struct Card: Identifiable {
let id = UUID()
let color: Color
let name: String
}
struct CardView: View {
let card: Card
var body: some View {
Rectangle()
.fill(card.color)
.frame(width: 120, height: 120)
.cornerRadius(10)
.overlay(
Text(card.name)
.font(.headline)
.foregroundColor(.white)
)
}
}
struct ContentView: View {
var cards: [Card] = [
Card(color: Color.red, name: "First Card"),
Card(color: Color.green, name: "Second Card"),
Card(color: Color.orange, name: "Third Card"),
]
@State var timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()
@State var movingDownSpeed = CGPoint(x: 0, y:10)
@State var cardPosition = CGPoint(x: UIScreen.main.bounds.size.width * 0.5, y:75)
var body: some View {
ZStack {
ForEach(cards) { card in
CardView(card: card)
.position(cardPosition)
.onReceive(self.timer) { _ in
moveDown()
}
}
}
}
func moveDown() {
if cardPosition.y < UIScreen.main.bounds.height - 120 {
withAnimation(.default){
cardPosition.y += movingDownSpeed.y
}
}
}
}