如何为SwiftUI中一组按钮的ForEach循环内的任何特定按钮添加修饰符? [英] How to add a modifier to any specific buttons inside a ForEach loop for an array of buttons in SwiftUI?
本文介绍了如何为SwiftUI中一组按钮的ForEach循环内的任何特定按钮添加修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据需要向单个按钮添加修改器?
我有一个ForEach
循环在0..<5
&;范围内运行,我需要根据按钮的状态添加一个.rotation3DEffect
在已单击按钮中的动画和另一个.opacity
在其余未单击按钮上的动画。
注意:我可以观察按钮操作中的任何状态值,然后将其更改为动画,但由于修改器应用于Button
本身在ForEach
循环中,我正在制作动画 应用于Foreach中的每个按钮。
@State private var rotationDegree = 0.0
@State private var selectedNum = 0
@State private var correctAnswer = 0 // comes from saved data
var body: some View {
ForEach(0..<5) { num in // image as a button, loops through their prefix name
Button {
selectedNum = (num == correctAnswer) ? num : 0
withAnimation {
// once clicked, will animate all 5 buttons, need only this clicked button to animate.
if (num == correctAnswer) {
rotationDegree += 360
}
}
} label: {
Image("imageName(num)")
}
.rotation3DEffect((.degrees((selectedNum == correctAnswer) ? rotationDegree : 0.0)), axis: (x: 0, y: (selectedNum == correctAnswer) ? 1 : 0, z: 0)) // animation I want to add to a specific button
}
}
推荐答案
import SwiftUI
struct AnimatedListView: View {
var body: some View {
VStack{
ForEach(0..<5) { num in
//The content of the ForEach goes into its own View
AnimatedButtonView(num: num)
}
}
}
}
struct AnimatedButtonView: View {
//This creates an @State for each element of the ForEach
@State private var rotationDegree = 0.0
//Pass the loops data as a parameter
let num: Int
var body: some View {
Button {
withAnimation {
rotationDegree += 360
}
} label: {
Image(systemName: "person")
Text(num.description)
}
.rotation3DEffect((.degrees(rotationDegree)), axis: (x: 0, y: 1, z: 0))
}
}
struct AnimatedListView_Previews: PreviewProvider {
static var previews: some View {
AnimatedListView()
}
}
这篇关于如何为SwiftUI中一组按钮的ForEach循环内的任何特定按钮添加修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文