How to pass @namespace to multiple Views in SwiftUI?

后端 未结 1 2012
清歌不尽
清歌不尽 2021-02-19 19:46

I\'m playing with the new Xcode 12 beta & SwiftUi 2.0. .matchedGeometryEffect() modifier is great to do Hero animations. There is a new property @Namespac

相关标签:
1条回答
  • 2021-02-19 20:18

    The @Namaspace is a wrapper for Namaspace.ID, and you can pass Namaspace.ID in argument to subviews.

    Here is a demo of possible solution. Tested with Xcode 12 / iOS 14

    struct HomeView: View {
        @Namespace var namespace
        @State var isDisplay = true
    
        var body: some View {
            ZStack {
                if isDisplay {
                    View1(namespace: namespace, isDisplay: $isDisplay)
                } else {
                    View2(namespace: namespace, isDisplay: $isDisplay)
                }
            }
        }
    }
    
    struct View1: View {
        let namespace: Namespace.ID
        @Binding var isDisplay: Bool
        var body: some View {
            VStack {
                Image("plant")
                    .resizable()
                    .frame(width: 150, height: 100)
                    .matchedGeometryEffect(id: "img", in: namespace)
                Spacer()
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.blue)
            .onTapGesture {
                withAnimation {
                    self.isDisplay.toggle()
                }
            }
        }
    }
    
    struct View2: View {
        let namespace: Namespace.ID
        @Binding var isDisplay: Bool
        var body: some View {
            VStack {
                Spacer()
                Image("plant")
                    .resizable()
                    .frame(width: 300, height: 200)
                    .matchedGeometryEffect(id: "img", in: namespace)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.red)
            .onTapGesture {
                withAnimation {
                    self.isDisplay.toggle()
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题