如何为SwiftUI中一组按钮的ForEach循环内的任何特定按钮添加修饰符?

人气:824 发布:2022-10-16 标签: foreach button animation modifier swiftui

问题描述

如何根据需要向单个按钮添加修改器?

我有一个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()
    }
}

477