Skip to content

properties 参数:仅匹配特定几何属性(如 size 或 position)

在 SwiftUI 中,matchedGeometryEffect 是一个强大的工具,可以帮助你在视图之间创建流畅的过渡动画。通过使用 properties 参数,你可以精确控制哪些几何属性会被匹配,从而实现更细致的动画效果。

1. 匹配特定几何属性

使用 properties 参数时,你可以选择仅匹配特定的几何属性,例如:

  • size:视图的大小
  • position:视图的位置

这种选择性匹配使得动画更加灵活,能够根据需求进行调整。比如,当你只想在视图大小变化时应用动画,而不想影响位置时,properties 参数就显得尤为重要。

2. 使用 .size 实现尺寸匹配动画

通过设置 properties 参数为 .size,你可以实现视图在大小变化时的动画效果。以下是一个简单的示例:

swift
@Namespace var animationNamespace

struct ContentView: View {
    @State private var isExpanded = false

    var body: some View {
        VStack {
            if isExpanded {
                Rectangle()
                    .fill(Color.blue)
                    .frame(width: 200, height: 200)
                    .matchedGeometryEffect(id: "rectangle", in: animationNamespace, properties: .size)
            } else {
                Rectangle()
                    .fill(Color.blue)
                    .frame(width: 100, height: 100)
                    .matchedGeometryEffect(id: "rectangle", in: animationNamespace, properties: .size)
            }
            Button("Toggle Size") {
                withAnimation {
                    isExpanded.toggle()
                }
            }
        }
    }
}

在这个示例中,点击按钮会触发矩形的大小变化,动画效果会非常流畅。

3. 使用 .position 实现位置匹配动画

同样地,使用 properties 参数为 .position,可以实现视图在位置变化时的动画效果。以下是一个示例:

swift
@Namespace var animationNamespace

struct ContentView: View {
    @State private var isMoved = false

    var body: some View {
        VStack {
            if isMoved {
                Circle()
                    .fill(Color.red)
                    .frame(width: 100, height: 100)
                    .matchedGeometryEffect(id: "circle", in: animationNamespace, properties: .position)
                    .offset(x: 100, y: 0)
            } else {
                Circle()
                    .fill(Color.red)
                    .frame(width: 100, height: 100)
                    .matchedGeometryEffect(id: "circle", in: animationNamespace, properties: .position)
            }
            Button("Move Circle") {
                withAnimation {
                    isMoved.toggle()
                }
            }
        }
    }
}

在这个例子中,点击按钮会使圆形移动,位置变化的动画效果同样流畅。

4. 结合使用

你可以结合使用 .size 和 .position 来实现更复杂的动画效果。通过灵活运用 properties 参数,你可以创建出令人惊叹的视图过渡效果,提升用户体验。✨

总之,properties 参数为你提供了强大的控制能力,让你能够精确匹配视图的几何属性,创造出更具吸引力的动画效果。继续探索,发挥你的创造力吧!🎉

本站使用 VitePress 制作