Home > database >  Why is my matchedGeometryEffect moving based on bottom right point?
Why is my matchedGeometryEffect moving based on bottom right point?

Time:10-27

I just tried to make some animation using matchedGeometryEffect.

However there's an error that the object is animated based on the bottom right point not the center.

The codes I used is here.:

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()
    }
}

With this codes, I got this result.:

enter image description here

Originally, I intended to make them move like this one. (got this from /

As you can see, they are moving based on the center point unlike mine.

I couldn't figure out what is the problem.

I tested it with the case using Image, Text things but it's acting in the same way.

Does this only happen in my laptop?

I would be really appreciated if you can let me know what point is wrong in here.

CodePudding user response:

Find below a fixed view - order of modifiers is important. Tested with Xcode 13 / iOS 14

Note: Slow Animation is activated for better visibility

demo

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)
            }
        }
    }
}
  • Related