Reputation: 13
I'm new to the iOS developer world and I'm currently stuck trying to figure out how to target a single View created in a ForEach loop.
Basically I have three shapes (flags), and I would like to add the functionality of having a flag rotate 360 degrees when the flag is tapped. I have the animation (rotation) part working but my problem is that I'm not able to figure out how to target the single flag that was tapped, instead the animations is executed by all three flags.
ForEach(0 ..< 3, id: \.self) { number in
Button(action: {
self.flagTapped(number)
withAnimation {
self.animationAmount += 360
}
self.askQuestion()
}) {
FlagImage(name: self.countries[number], number: number)
}
.rotation3DEffect(.degrees(self.animationAmount), axis: (x: 0, y: 1, z: 0))
}
This is my code so far, what it does is what I explained before, it does the 360 rotation but for all three flags instead of the one that is being tapped, I also tried doing something with onTapGesture but that didn't seem to work. I would appreciate some help, thank you!
Upvotes: 1
Views: 954
Reputation: 257711
Here is a demo how this could be done (I used some standard things in your snapshot due to absent custom values, but the idea should be obvious).
struct TestTargetButton: View {
let countries = ["shield", "triangle", "square"]
@State var selection: Int? = nil
@State var animationAmount: Double = 0
var body: some View {
HStack {
ForEach(0 ..< 3, id: \.self) { number in
Button(action: {
self.selection = number
withAnimation {
self.animationAmount += 360
}
}) {
Image(systemName: self.countries[number])
.resizable()
.frame(width: 50, height: 50)
.padding()
}
.rotation3DEffect(.degrees(self.selection == number ? self.animationAmount : 0), axis: (x: 0, y: 1, z: 0))
}
}
}
}
Upvotes: 3