首页 > 解决方案 > 为什么我的matchedGeometryEffect 基于右下角移动?

问题描述

我只是尝试使用matchedGeometryEffect 制作一些动画。

但是,对象是基于右下角而不是中心进行动画处理的错误。

我使用的代码在这里。:

import SwiftUI

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

            if show {
                Rectangle()
                    .frame(width: 200, height: 200)
                    .matchedGeometryEffect(id: "animation", in: animation)
            }
        }
    }
}

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

使用此代码,我得到了以下结果:

在此处输入图像描述

本来,我是打算让它们像这样动的。(从https://swiftui-lab.com/matchedgeometryeffect-part1得到这个)

/

如您所见,它们与我的不同,它们基于中心点移动。

我无法弄清楚是什么问题。

我使用图像,文本的东西对它进行了测试,但它的行为方式相同。

这只发生在我的笔记本电脑上吗?

如果您能告诉我这里出了什么问题,我将不胜感激。

标签: iosswiftswiftui

解决方案


在固定视图下方查找 - 修饰符的顺序很重要。使用 Xcode 13 / iOS 14 测试

注意:激活慢速动画以获得更好的可见性

演示

struct Test: View {
    @Namespace private var ns
    @State var show = false

    var body: some View {
        HStack {
            if show != true {
                Rectangle()
                    .matchedGeometryEffect(id: "animation", in: ns) // << here !!
                    .frame(width: 50, height: 50)
            }
            Spacer()
            Button(action: {
                withAnimation {
                    show.toggle()
                }
            }) {
                Text("Switch")
            }
            Spacer()

            if show {
                Rectangle()
                    .matchedGeometryEffect(id: "animation", in: ns) // << here !!
                    .frame(width: 200, height: 200)
            }
        }
    }
}

推荐阅读