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

SwiftUI新版Scoped Animation Modifier使用问题求助

WWDC23 新版animation视图修饰器未生效问题解析

你遇到的问题核心是外部withAnimation的动画优先级高于视图本地的.animation(_:content:)修饰器。

当点击「Reveal」按钮时,withAnimation(.bouncy(duration: 0.5))会创建一个全局动画事务,所有受offset变化影响的视图(包括绿色矩形)都会使用这个事务里的动画,完全覆盖了你给绿色矩形设置的本地0.01秒弹性动画。

如果想让绿色矩形强制使用自己的动画,不管外部的withAnimation,你需要用.transaction修饰器直接替换当前视图的事务动画,而非新版的.animation(_:content:)。修改后的代码如下:

struct ScopedAnimation: View {
    @State private var offset = 0.0
    
    var body: some View {
        VStack {
            ZStack {
                Color.red
                Text("Hello")
                    .foregroundStyle(.white)
                Color.green
                    .offset(x: offset)
                    .transaction { tx in
                        // 强制替换当前视图的事务动画
                        tx.animation = .bouncy(duration: 0.01)
                    }
            }
            .frame(width: 100, height: 50)
            Button("Reveal") {
                withAnimation(.bouncy(duration: 0.5)) { offset = -100 }
            }
            Button("Reset") {
                withAnimation(.none) { offset = 0 }
            }
        }
    }
}

补充说明新版.animation(_:content:)的正确使用场景:它适合在没有外部withAnimation上下文时,为视图的特定属性变化指定动画。比如按钮点击时不用withAnimation包裹,直接修改offset,绿色矩形的本地动画就会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:50:11