I have a VStack with 4 buttons(potential answers in a multiple choice quiz).
See below for the code.
Currently, when the user clicks on the button containing the correct answer, the old text animates into the new text.
What I want is not that only the text animates, but the whole button. ie. the button animates off screen to the left, and 4 new buttons animate on screen from the right.
I tried adding a .transition(.move(.leading) modifer to the vstack of the button. that worked partly. The buttons now animate on and off screen to the left side.
But that is not what I want. I want that the "old" buttons move away to the left, and that the new buttons move on from the right.
Anybody any sugestions on how to do that?
Thx!
The ButtonView
:
struct ButtonView: View {
var answer: Answer?
var text: String = ""
var useText: Bool
@State var color = Color(.label)
@State var background = Color(.systemGray6)
var width: CGFloat = 200
var height: CGFloat = 50
@State private var pressed = false
@State private var attempts: CGFloat = 0
var action: (Answer?) -> Void
var body: some View {
Text(useText ? text : answer!.body)
.foregroundColor(.white)
.font(.title2)
.bold()
.frame(width: width, height: height, alignment: .center)
.colorMultiply(self.color)
.background(background)
.onTapGesture {
pressed = true
withAnimation(.easeInOut(duration: 0.6)) {
if !(answer?.isCorrect ?? true) { attempts += 1 }
self.color = Color(.systemBackground)
self.background = Color(.systemOrange)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
withAnimation(.easeIn) {
self.color = Color(.label)
self.background = Color(.systemGray6)
action(answer)
pressed = false
}
}
}
.cornerRadius(10)
.animation(.default)
.disabled(pressed)
.shake(attempts: attempts)//I have a extension in my code. it is not needed for this question as it is only triggered when the pressed button contained a false answre
}
}
I also use this view for other buttons. Therefore I have the useText and text variables.
The code for displaying the 4 buttons:
VStack(spacing: 20) {
ForEach(viewModel.answers, id: \.self) { answer in
ButtonView(answer: answer, useText: false) { buttonAnswer in
viewModel.check(answer: buttonAnswer!)
}.transition(.move(edge: .leading))
}
}.disabled(viewModel.disabled)