It’s day 34 of the 100 Days of SwiftUI! Yesterday, we learned about advanced animations. Today, we review what we learned over the course of this technique project, as well as face a few challenges.
This post will end here, for now. You see, the challenges are quite, well, challenging. I’ve not been able to finish them just yet, but as soon as I’ve done so, I’ll update this post.
Update 12/08/22: challenges completed!
I came back with a new view on the challenge and I managed to solve them quite easily. The most difficult part was tracking which flag the user selected. After figuring that out, the rest was easy!
SwiftUI animation challenge #1
The first challenge is to make the flag we selected spin around 360 degrees on the Y axis.
The first thing we need to do is figure out how to track which flag the user selected. To accomplish this, we add a new State
property to track which flag the user selected. We default this to -1, which means that no flag is selected by default.
@State private var selectedFlag = -1
Next, we add set the our selectedFlag
to the number of the flag the user chooses in the flagTapped
function.
func flagTapped(_ number: Int) {
selectedFlag = number
// rest of function
}
Finally, we reset the selectedFlag
property back to a value of -1 whenever a new question is asked.
func newQuestion() {
countries.shuffle()
correctAnswer = Int.random(in: 0...2)
selectedFlag = -1 // <------
questionCounter+=1
}
With the set up to track the users selection out of the way, the remainder of the challenges becomes quite easy. The rotation is handled by a rotation3DEffect()
.
ForEach(0..<3) { number in
Button {
flagTapped(number)
}
label: {
Image(countries[number])
.renderingMode(.original)
.clipShape(Capsule())
.shadow(radius: 5)
.rotation3DEffect(.degrees(selectedFlag == number ? 360: 0), axis: (x: 0, y: 1, z: 0))
.animation(.default, value: selectedFlag)
}
}
SwiftUI animation challenge #2
The second challenge is to make the flags that were not selected fade out to 25%. SwiftUI features an .opacity()
modifier, which we’ll implement here, with a ternary operator inside to control which flags are faded out.
.opacity(selectedFlag == -1 || selectedFlag == number ? 1.0 : 0.25)
SwiftUI animation challenge #3
The third and final challenge was to add a third effect of our choosing to the two flags the user didn’t choose. I chose to make them scale down.
.scaleEffect(selectedFlag == -1 || selectedFlag == number ? 1 : 0.5)
Wrap up
And that’s it for day 34! It certainly took a little while for me to come to the solution, I’m currently at day 47, but there it is.
Thank you for this. I was battering my head against a wall for days trying to make the damn flags spin correctly until I gave up, googled, and found this post!
You’re welcome, I’m glad it helped! I was up against it for a good long while as well. 🙂