【问题标题】:Matched Geometry Effect in SwiftUI is not workingSwiftUI 中的匹配几何效果不起作用
【发布时间】:2021-12-28 16:25:47
【问题描述】:

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

感谢您的帮助,Boothosh

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    在 SwiftUI 中,修饰符的顺序很重要。这与matchedGeometryEffect(id:in:properties:anchor:isSource:) 相同。

    如果您希望矩形在中心展开,则需要将几何图形在中心对齐。为此,我们将拥有相同大小的Rectangles。这意味着Rectangles 都将附加matchedGeometryEffect 修饰符,并在其后添加 then 样式。

    代码:

    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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-14
      • 2021-12-08
      • 1970-01-01
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 2017-04-25
      相关资源
      最近更新 更多