【问题标题】:How to animate particular button from ForEach in SwiftUI?如何在 SwiftUI 中为 ForEach 中的特定按钮设置动画?
【发布时间】:2020-12-22 03:23:19
【问题描述】:

我有一个动画按钮的问题。我使用 ForEach 方法创建了它们。我的应用程序的布局由 3 个标志组成。我们有文字说我们必须选择特定国家的国旗,如果我们选择正确的国旗,我们就会获得积分。

我想在按下特定按钮时为其设置动画。答案是否正确并不重要。

我创建这些按钮的代码如下所示:

ForEach(0 ..< 3) { number in
    Button(action: {
        withAnimation {
            if number == self.correctAnswer {
                self.animationAmount += 360
            }
        }
        
        self.flagTapped(number)
    }) {
        ImageView(myImage: self.countries[number])
    }
    .rotation3DEffect(.degrees(number == self.correctAnswer ? self.animationAmount : 0), axis: (x: 0, y: 1, z: 0))
    .opacity(self.showAnimation && number != self.correctAnswer ? 0.25 : 1)
    .background(self.showAnimation && number != self.correctAnswer ? Color.red: nil)
}

self.flagTapped(number) 将showAnimation 切换为true。

【问题讨论】:

    标签: swift animation button foreach swiftui


    【解决方案1】:

    这是一种可能的替代方法 - 更合适的做法是将按钮移动到单独的视图中,并让它在需要时自行设置动画。

    在一些复制的简化代码上准备了演示(由于提供的快照中缺少部分)。使用 Xcode 12 / iOS 14 测试。

    struct DemoView: View {
        let countries = ["flag-1", "flag-2", "flag-3", "flag-4"]
    
        @State private var number: Int = -1
        let correctAnswer = 1
        var body: some View {
            VStack {
                ForEach(0 ..< 3) { number in
                    FlagButton(number: number, image: self.countries[number], answer: correctAnswer){
                        self.flagTapped(number)
                    }
                }
            }
        }
    
        private func flagTapped(_ number: Int) {
            self.number = number
        }
    }
    
    
    struct FlagButton: View {
        let number: Int
        let image: String
        let answer: Int
        var showAnimation = false
        let action: () -> ()
    
        @State private var animationAmount = Double.zero
        var body: some View {
            Button(action: {
                if self.number == self.answer {
                    self.animationAmount += 360
                }
                action()
            }) {
                Image(image)
            }
            .rotation3DEffect(.degrees(number == answer ? self.animationAmount : 0), axis: (x: 0, y: 1, z: 0))
            .opacity(self.showAnimation && number != answer ? 0.25 : 1)
            .background(self.showAnimation && number != answer ? Color.red: nil)
            .animation(.default)
        }
    }
    

    【讨论】:

    • 我试图实现你的想法,它让我更接近最终的解决方案,但我仍然无法克服一件事。当单击正确的按钮时,我想将 2 个错误的按钮设置为 75% 的不透明度,并为我单击的按钮设置错误的背景设置为红色。你能帮我解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    相关资源
    最近更新 更多