我想知道为什么我的 matchedGeometryEffect
没有按预期工作。我做错什么了吗?因为this guy (3:15)也做了同样的事情,看起来流畅多了。我在 M1 MacBook Air 上运行代码,这意味着速度可能不是问题。
这是我的代码:
struct ContentView: View {
@Namespace var namespace
@State var bool = true
var body: some View {
HStack{
if bool {
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(Color.red)
.padding()
.onTapGesture {
withAnimation(.spring(response: 0.5, dampingFraction: 0.7)){
bool.toggle()
}
}
.matchedGeometryEffect(id: "id", in: namespace)
} else {
Rectangle()
.frame(width: 200, height: 200)
.foregroundColor(Color.red)
.matchedGeometryEffect(id: "id", in: namespace)
}
}
}
}
感谢您的帮助,布托什
最佳答案
在 SwiftUI 中,修饰符顺序很重要。这与matchedGeometryEffect(id:in:properties:anchor:isSource:)
相同。 .
如果您希望矩形在中心展开,则需要几何图形在中心对齐。为此,我们将拥有相同大小的矩形。这意味着两个 Rectangle
都将附加 matchedGeometryEffect
修饰符,并在之后设置样式。
代码:
HStack {
if bool {
Rectangle()
.matchedGeometryEffect(id: "id", in: namespace) // <- Here
.frame(width: 100, height: 100)
.foregroundColor(Color.red)
.padding()
.onTapGesture {
withAnimation(.spring(response: 0.5, dampingFraction: 0.7)) {
bool.toggle()
}
}
} else {
Rectangle()
.matchedGeometryEffect(id: "id", in: namespace) // <- Here
.frame(width: 200, height: 200)
.foregroundColor(Color.red)
}
}
关于swift - SwiftUI 中的匹配几何效果不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70509787/