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

为什么我的matchedGeometryEffect动画以右下角而非中心点为锚点运动?

这个问题不是设备独有,是matchedGeometryEffect在跨位置条件渲染场景下的默认参数匹配异常导致的。
核心原因是系统插值计算时错误使用了右下角作为锚点,你只需要给两个矩形的matchedGeometryEffect修饰符补充显式的匹配属性和锚点参数即可。

修改后的代码如下:

import SwiftUI

struct Test: View {
    @Namespace private var animation
    @State var show = false
    
    var body: some View {
        HStack {
            if !show {
                Rectangle()
                    .frame(width: 50, height: 50)
                    .matchedGeometryEffect(id: "animation", in: animation, properties: .frame, anchor: .center)
            }
            Spacer()
            Button(action: {
                withAnimation(.easeInOut) {
                    show.toggle()
                }
            }) {
                Text("Switch")
            }
            Spacer()

            if show {
                Rectangle()
                    .frame(width: 200, height: 200)
                    .matchedGeometryEffect(id: "animation", in: animation, properties: .frame, anchor: .center)
            }
        }
        .padding()
        .frame(maxHeight: .infinity)
    }
}

struct Test_Previews: PreviewProvider {
    static var previews: some View {
        Test()
    }
}

如果修改后仍有轻微偏移,可以给两个Rectangle都添加.transition(.identity),禁用系统默认的透明度过渡,完全交给matchedGeometryEffect接管动画逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:45:08