简体   繁体   中英

matchedGeometryEffect just jumps and doesn't animate

I am trying to animate an image from the centre to the top of my screen with matchedGeometryEffect . However, it just jumps. This is a simplified version of my view, which is essentially what I'm trying to do:

struct MyView: View {
  @Namespace private var animation
  @State private var showSplash = true

  var body: some View {
    if showSplash {
      Image("SplashIcon")
        .matchedGeometryEffect(id: "icon", in: animation)
        .frame(maxWidth: .infinity)
        .task {
          try? await Task.sleep(nanoseconds: 1_500_000_000)
          withAnimation {
            showSplash.toggle()
          }
        }
    } else {
      VStack {
        Image("SplashIcon")
          .matchedGeometryEffect(id: "icon", in: animation)
          .frame(maxWidth: .infinity)
        Spacer()
      }
    }
  }

How do I fix this?

See comments...

Actually works as well in Preview.. if, and it is always better, to put condition into container, like

  var body: some View {
        VStack {            // << this one !!
            if showSplash {
                Image("SplashIcon")
                    .matchedGeometryEffect(id: "icon", in: animation)
                    .frame(maxWidth: .infinity)
                    .task {
                        try? await Task.sleep(nanoseconds: 1_500_000_000)
                        withAnimation {
                            showSplash.toggle()
                        }
                    }
            } else {
                VStack {
                    Image("SplashIcon")
                        .matchedGeometryEffect(id: "icon", in: animation)
                        .frame(maxWidth: .infinity)
                    Spacer()
                }
            }
        }
    }

演示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM