You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复iOS 15.0中'animation'已被弃用的警告?

解决SwiftUI动画弃用警告并实现循环移动效果

原代码中使用的无参数.animation()修饰符在iOS15之后被弃用,Apple推荐使用**animation(_:value:)(绑定触发动画的状态变量)或withAnimation**(包裹状态变化代码)来明确控制动画触发时机,避免意外的动画触发。

重构后的代码实现

我们通过绑定一个控制位置的状态变量,结合新的动画API来实现需求,同时消除警告:

struct CloudView: View {
    // 控制星星的X轴偏移量
    @State private var offsetX: CGFloat = 0
    // 标记当前移动方向(左/右)
    @State private var isMovingLeft = true
    
    var body: some View {
        Image("star.png")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 300, height: 300)
            .padding(.top, -670)
            .offset(x: offsetX)
            // 使用新的animation API,绑定offsetX作为触发值
            .animation(Animation.linear.speed(0.05), value: offsetX)
            .onAppear {
                startCycleAnimation()
            }
    }
    
    // 启动循环移动的逻辑
    private func startCycleAnimation() {
        Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { timer in
            if isMovingLeft {
                // 向左移动到目标位置
                offsetX = -270
            } else {
                // 向右移动到目标位置(可根据需求调整数值)
                offsetX = 270
            }
            
            // 到达目标位置后,返回起点并切换方向
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                offsetX = 0
                isMovingLeft.toggle()
            }
        }
    }
}

关键修改点说明

  • 移除了原代码中逻辑矛盾的show变量(原代码onAppear中先切换show又立刻设为true,实际无效果),改用offsetX直接控制星星位置。
  • 使用.animation(Animation.linear.speed(0.05), value: offsetX)替代旧的.animation(),明确只有当offsetX变化时才触发动画,消除弃用警告。
  • 通过定时器Timer实现循环移动逻辑:先向左移动→返回起点→向右移动→返回起点,重复该过程,你可以根据需求调整移动的目标位置和时间间隔。

另一种简化实现(自动来回移动)

如果你的需求是星星在左右两端之间自动来回移动,不需要单独返回起点的步骤,可以更简洁地实现:

struct CloudView: View {
    @State private var offsetX: CGFloat = -270
    
    var body: some View {
        Image("star.png")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 300, height: 300)
            .padding(.top, -670)
            .offset(x: offsetX)
            .animation(Animation.linear.speed(0.05).repeatForever(autoreverses: true), value: offsetX)
            .onAppear {
                offsetX = 270
            }
    }
}

这里利用repeatForever(autoreverses: true)让动画自动来回播放,onAppear时设置目标偏移量,动画会自动从初始的-270移动到270,然后反向回到-270,循环往复。

内容的提问来源于stack exchange,提问作者kkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 22:00:56