当我使用匹配的几何视图修饰符时,我总是收到警告。
Multiple inserted views in matched geometry group Pair<String, ID>(first: "id1", second: SwiftUI.Namespace.ID(id: 8)) have isSource: true, results are undefined.
当动画仍然有效时,我想了解为什么我会收到这个警告,以及如何解决这个问题。
这是我制作的动画,有什么想法怎么摆脱警告吗?
使用以下代码
struct ContentView: View {
@State var details = false
@Namespace var animation
var body: some View {
ZStack {
HStack {
Rectangle()
.frame(width: 100, height: 100)
.matchedGeometryEffect(id: "id1", in: animation)
.onTapGesture {
withAnimation {
details.toggle()
}
}
Spacer()
}
.zIndex(1)
if details == true {
AnotherView(details: $details, animation: animation)
.zIndex(2)
}
}
}
}
struct AnotherView: View {
@Binding var details: Bool
var animation: Namespace.ID
var body: some View {
ZStack {
Color.red
Rectangle()
.frame(width: 300, height: 300)
.matchedGeometryEffect(id: "id1", in: animation)
.onTapGesture {
withAnimation {
details.toggle()
}
}
}
}
}
发布于 2020-10-28 22:18:41
问题是同时在屏幕上有两个视图(即使第二个视图包含第一个视图,第一个视图仍然在屏幕上)。使用.matchedGeometryEffect
,一个视图在逻辑上取代了另一个视图,因此在绘制第二个视图时需要删除第一个视图。您可以通过只在Rectangle
时绘制第一个!details
来修复这个问题。
另外,为了更干净的效果,我将.matchedGeometryEffect
移动到Rectangle
s的第一个修饰符。
struct ContentView: View {
@State var details = false
@Namespace var animation
var body: some View {
ZStack {
HStack {
if !details {
Rectangle()
.matchedGeometryEffect(id: "id1", in: animation)
.frame(width: 100, height: 100)
.onTapGesture {
withAnimation {
details.toggle()
}
}
}
Spacer()
}
.zIndex(1)
if details {
AnotherView(details: $details, animation: animation)
.zIndex(2)
}
}
}
}
struct AnotherView: View {
@Binding var details: Bool
var animation: Namespace.ID
var body: some View {
ZStack {
Color.red
Rectangle()
.matchedGeometryEffect(id: "id1", in: animation)
.frame(width: 300, height: 300)
.onTapGesture {
withAnimation {
details.toggle()
}
}
}
}
}
.matchedGeometryEffect
Documentation状态(粗体后加):
如果在同一事务中插入另一个具有相同键的视图,则系统将在窗口空间内插入其框架矩形,使之看起来有一个视图从其旧位置移动到其新位置。
通常的转换机制定义了在过渡期间如何呈现这两个视图(例如,淡入/退出、缩放等),matchedGeometryEffect()修饰符只安排要链接视图的几何图形,而不是它们的呈现。
如果在具有isSource = true的组中当前插入的视图的数量并不完全是一个未定义的结果,因为它不清楚哪个是源视图。
发布于 2020-10-29 05:13:04
下面的变体也适用于预览版(由@vacawama提出,只是以防万一)。
用Xcode 12.0 / iOS 14测试
struct ContentView: View {
@State var details = false
@Namespace var animation
var body: some View {
ZStack {
HStack {
if !details {
Rectangle()
.matchedGeometryEffect(id: "id1", in: animation)
.frame(width: 100, height: 100)
.onTapGesture {
details.toggle()
}
}
Spacer()
}.animation(.default, value: details)
if details {
AnotherView(details: $details, animation: animation)
}
}.animation(.default, value: details)
}
}
struct AnotherView: View {
@Binding var details: Bool
var animation: Namespace.ID
var body: some View {
ZStack {
Color.red
Rectangle()
.matchedGeometryEffect(id: "id1", in: animation)
.frame(width: 300, height: 300)
.onTapGesture {
details.toggle()
}
}
}
}
https://stackoverflow.com/questions/64581837
复制相似问题