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

如何通过matchedGeometryEffect实现文本从上到下的动画(当前动画反向)

SwiftUI 修正向下动画方向问题

你的问题出在matchedGeometryEffect的使用逻辑上:你用递增的counter作为id,每次点击按钮都会生成新的id,导致系统无法正确关联上下两个Text的几何关系;同时isSource的设置没有配合状态切换来实现正确的源→目标映射。

修正方案

改用布尔状态来控制动画的源和目标,同时将动画统一应用到状态切换时机,避免重复设置动画:

struct AnimDown: View {
    
    @State private var textAnim = "2344"
    @State private var triggerAnim = false // 控制动画触发的状态
    @Namespace private var ns1

    var body: some View {
        VStack {
            Text(textAnim)
                .matchedGeometryEffect(id: "animateText", in: ns1, isSource: !triggerAnim)
                .foregroundColor(.blue)
          
            Text(textAnim)
                .matchedGeometryEffect(id: "animateText", in: ns1, isSource: triggerAnim)
                .foregroundColor(.red)
          
            Button("Move Down") {
                textAnim = String("\(Int.random(in: 1..<99))")
                withAnimation(.easeInOut) {
                    triggerAnim.toggle()
                }
            }
            .padding(.top, 20)
        }
    }
}

原理说明

  1. 统一使用固定id "animateText",让SwiftUI识别两个Text属于同一组动画关联元素
  2. 通过triggerAnim布尔值切换isSource属性:
    • 初始状态triggerAnim = false,蓝色Text作为动画源,红色Text作为目标
    • 点击按钮时切换状态,触发动画后蓝色Text的几何属性会过渡到红色Text的位置,实现向下移动的效果
  3. 用withAnimation包裹状态切换,统一控制动画触发时机,避免多组件重复设置动画导致的逻辑冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:12:11