SwiftUI:如何消除使用 MatchedGeometryEffect 时的故障?

问题描述 投票:0回答:0

我正在尝试在两个视图之间创建过渡。由于我目前正在测试过渡,因此两个视图都非常简单。

第一个视图“Playground5”包含一个小矩形,我想将其转换到第二个视图“Playground 6”,其中包含一个相同颜色的全屏矩形。

我希望过渡到向外“扩展”和“向内”。

从 Playground5 到 Playground6 时,过渡效果很好。

但是当我想从playground6转到playground5,即从全屏矩形到小矩形时。过渡出现了一个小故障。

关于如何解决这个问题有什么想法吗?

import SwiftUI

struct Playground5: View {
    @State private var expandRectangle = false
    @Namespace private var namespace

    var body: some View {
        ZStack {
            if expandRectangle {
                Playground6(expandRectangle: $expandRectangle, namespace: namespace)
            } else {
                Rectangle()
                    .foregroundColor(Color.red)
                    .frame(width: expandRectangle ? 400 : 200, height: expandRectangle ? 600 : 400)
                    .onTapGesture {
                        withAnimation {
                            expandRectangle.toggle()
                        }
                    }
                    .matchedGeometryEffect(id: "rectangle", in: namespace)
            }
        }
        .ignoresSafeArea(.all)
    }
}

struct Playground6: View {
    @Binding var expandRectangle: Bool
    var namespace: Namespace.ID
    
    var body: some View {
            Rectangle()
                .foregroundColor(Color.red)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .matchedGeometryEffect(id: "rectangle", in: namespace)
                .ignoresSafeArea(.all)
            .onTapGesture {
                    withAnimation {
                        expandRectangle.toggle()
                    }
                } 
    }
}

ios animation swiftui view transition
© www.soinside.com 2019 - 2024. All rights reserved.