我正在使用新的 Xcode 12 beta 和 SwiftUi 2.0。 .matchedGeometryEffect()
修改器非常适合做英雄动画。有新楼盘@Namespace
是在 SwiftUI 中引入的。它 super 酷。工作真棒。
我只是想知道是否有可能将命名空间变量传递给多个 View ?
这是我正在研究的一个例子,
struct HomeView: View {
@Namespace var namespace
@State var isDisplay = true
var body: some View {
ZStack {
if isDisplay {
VStack {
Image("share sheet")
.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()
}
}
} else {
VStack {
Spacer()
Image("share sheet")
.resizable()
.frame(width: 300, height: 200)
.matchedGeometryEffect(id: "img", in: namespace)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.red)
.onTapGesture {
withAnimation {
self.isDisplay.toggle()
}
}
}
}
}
}
它工作正常。但是如果我想提取
Vstack
作为 subview ,下图显示我已将第一个 VStack 提取到 subview 中。我得到了赞美
Cannot find 'namespace' in scope
有没有办法跨多个 View 传递命名空间?
最佳答案
@Namespace
是 Namespace.ID
的包装器,您可以通过 Namespace.ID
在对 subview 的争论中。
这是可能的解决方案的演示。使用 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()
}
}
}
}
关于swiftui - 如何将@namespace 传递给 SwiftUI 中的多个 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63130663/