SwiftUI数字逐步递增动画效果
SwiftUI数字逐步递增动画效果

SwiftUI数字逐步递增动画效果

需求描述

在开发《方方块》游戏的过程中,考虑到分数直接相加,效果不是很好,因此考虑让分数在变化的过程中,能够看到分数逐步递增的动画效果。

在这里使用Timer逐步递增,完成平滑增加数值的动画。

代码示例

import SwiftUI

struct ScoreView: View {
    @State private var score = 28
    private let targetScore = 55
    private let incrementStep = 1  // 每次增加多少
    private let animationSpeed = 0.05  // 速度(秒)

    var body: some View {
        VStack {
            Text("Score: \(score)")
                .font(.largeTitle)
                .bold()
                .animation(.easeOut, value: score) // 让文本更新时有动画效果

            Button("Increase Score") {
                increaseScore(to: targetScore)
            }
        }
    }

    func increaseScore(to newScore: Int) {
        Timer.scheduledTimer(withTimeInterval: animationSpeed, repeats: true) { timer in
            if score < newScore {
                score += incrementStep
            } else {
                timer.invalidate() // 目标值达到时停止
            }
        }
    }
}

主要的代码是increaseScore方法,通过Timer类设置计时器,根据设定的animationSpeed速度,更新分数。

当分数到达目标后,执行timer.invalidate()停止计时器。

总结

使用 .animation(.easeOut, value: score) 让 Text 在更新时有平滑的过渡效果。

在我的实际代码中,也是通过这一个方法,完成数字逐步递增的动画效果。

// 更新积分
increaseScore(to: GameScore + EliminationRewards)

// 分数递增动画
func increaseScore(to newScore: Int) {
    Timer.scheduledTimer(withTimeInterval: animationSpeed, repeats: true) { timer in
        if GameScore < newScore {
            GameScore += incrementStep
        } else {
            timer.invalidate() // 目标值达到时停止
        }
    }
}

相关文章

Swift和Foundation框架创建和管理定时任务的Timer类:https://fangjunyu.com/2024/12/14/swift%e5%92%8cfoundation%e6%a1%86%e6%9e%b6%e5%88%9b%e5%bb%ba%e5%92%8c%e7%ae%a1%e7%90%86%e5%ae%9a%e6%97%b6%e4%bb%bb%e5%8a%a1%e7%9a%84timer%e7%b1%bb/

如果您认为这篇文章给您带来了帮助,您可以在此通过支付宝或者微信打赏网站开放者。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注