swift - SwiftUI 中的匹配几何效果不起作用

标签 swift swiftui

我想知道为什么我的 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/

相关文章:

ios - Swift 和 SwiftUI 从 TextField 字符串绑定(bind)到模型已发布的可选 Integer 属性

objective-c - 检查初始化方法的完成 block 内 Swift 变量的值

ios - 如何使用 SQLite.swift 使用 "start of month"sqlite 日期修饰符

swift - 使用 SwiftUI 中事件文本字段的值更新非事件文本字段

swift - 使用 SwiftUI 组合刷新 token

swiftui - 想要为延时(时间轴)重新创建以下 UI

ios - Swift- 错误 : Variable 'self.___' used before being initialized

ios - 如何从文本文件中读取选定的列

swift - SwiftUI 中的单元测试

swiftui - 如何让 TextEditor 显示多行?