【问题标题】:Stop animation on SwiftUI button in a ForEach stack在 ForEach 堆栈中的 SwiftUI 按钮上停止动画
【发布时间】:2020-04-13 10:10:31
【问题描述】:

概述

我正在使用#100daysofswiftui 学习 SwiftUI,我在第 32 天学习。这是一个简单的旗帜游戏,我拥有和排列国家名称并随机选择正确答案

@State private var paises = ["Poland", "Russia", "Spain", "UK", "US"].shuffled()
@State private var respuestaCorrecta = Int.random(in: 0...2)

然后我用 forEach 制作按钮

ForEach(0 ..< 3){ numero in
    //right answer
    if numero == self.respuestaCorrecta {
        Button(action:{
            self.BanderaSeleccionada(numero)
        }){
            Bandera(imagen: self.paises[numero])
        }    .rotation3DEffect(.degrees(self.GoodAnimationAmount),
                               axis: (x: 0, y: 1, z: 0))
    } else {
        Button(action:{
            self.BanderaSeleccionada(numero)
        }){
            Bandera(imagen: self.paises[numero])
        } 
    }
}

如果用户选择了正确的按钮,我会这样做:

func BanderaSeleccionada(_ numero: Int)  {
    if numero == respuestaCorrecta{
        tituloPuntaje = "Respuesta correcta"
        textoPuntaje = "¡Bien Hecho!"
        self.puntaje += 1

        self.GoodAnimationAmount += 360
        withAnimation(.interpolatingSpring(stiffness: 5, damping: 1)) {
                             self.GoodAnimationAmount += 360
        }


        withAnimation {
                       self.TheOthersAnimationAmount -= 0.75
                   }


    }else{
        withAnimation{ 
            self.WrongAnimationAmount += 4
        }

        tituloPuntaje = "Respuesta incorrecta"
        textoPuntaje = "Has elegido \(paises[numero])"
    }

    mostrarPuntuajeMasAlto = true
}

让旋转成为正确的答案

问题

问题在于值的变化,如果下一个右按钮与上一个按钮相同,则标志会继续旋转,因此会破坏正确答案,当正确答案是另一个时,动画就会消失,所以我有点对 Swift 的工作方式感到困惑。

我现在能做的最好的事情就是删除.interpolatingSpring(stiffness: 2, damping: 1),但我想在国家/地区洗牌时停止 interpolatingSpring。

func hacerPregunta() {
    self.GoodAnimationAmount = 0
    self.WrongAnimationAmount = 0
    self.TheOthersAnimationAmount = 1.0

    respuestaCorrecta = Int.random(in: 0...2)
    paises.shuffle()   
}

【问题讨论】:

    标签: swift swiftui ios-animations


    【解决方案1】:

    当跳转到下一个问题时,应该更新正确答案 respuestaCorrecta = -1 而不是像这样随机 respuestaCorrecta = Int.random(in: 0...2) .

    【讨论】:

    • 这可能会导致应用程序崩溃,te rigthAnswer 必须是 0,1 或 2 才能成为数组的选项。
    • @MisaelLanderos 你能告诉我BanderaSeleccionada函数中的代码吗
    猜你喜欢
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2021-02-17
    相关资源
    最近更新 更多