I want to build a View with ZStack of cards which get info from an array. Cards have to swipe to the left and to the right by .gesture modifier, without any other buttons. What I want is when the current card is displayed, the next card isn’t seen. And when the current card goes away, the next card automatically is shows up.
Long story short, I want to make swipe cards UI like in Tinder or Quizlet, without using Foreach and laying out all the cards at once (there may be a lot of them)
I tried to loop through ForEach(array.indices) without any modifiers, and all cards displayed simultaneously in a stack, but I want them to update as user swipes the current card. I don’t know of other ways to write code for updating views (beginner here).
struct ContentView: View {
@EnvironmentObject var model: Model
var body: some View {
VStack {
ZStack {
RoundedRectangle(cornerRadius: 20)
.aspectRatio(CGSize(width: 150, height: 300), contentMode: .fit)
.foregroundColor(.white)
.shadow(radius: 5)
.padding(50)
ForEach(model.flashcard.reversed()) { card in
AllCardView(flashcard: Flashcard(front: card.front, back: card.back))
}
.padding()
}
}
}
}
2
Answers
Approach:
ZStack
to stack the cardsDragGesture
on the card.onChanged
and.onEnded
on the gesture to move the cardwithAnimation { }
to animate the value changesGiven below is a crude implementation, you could use it as a guidance and refine it:
Card:
Model:
CardView:
ContentView:
You need some more Views to transform the data you want to display, e.g.
Name the Views however you like.