使用 matchedGeometryEffect
的 SwiftUI 过渡效果。
在过渡开始时(当视图被插入视图层级中时),该视图将被放置在与源视图几何形状相匹配的位置,源视图具有匹配的 id 和 namespace。然后它将移动到它的正常位置,不再与源视图匹配。当它从视图层级中移除时,过程相反。
推荐
复制 FromMatchedGeometry.swift 到你的项目中。
SPM
使用 Swift Package Manager 添加此仓库:https://github.com/nikstar/FromMatchedGeometry
import FromMatchedGeometry
struct ContentView: View {
@State private var showInsertedView = false
@Namespace private var ns
var body: some View {
VStack {
SourceView()
.matchedGeometryEffect(id: 0, in: ns, isSource: true)
.onTapGesture { showInsertedView.toggle() }
if showInsertedView {
TargetView()
.transition(
.fromMatchedGeometry(id: 0, in: ns)
)
}
}
.animation(.bouncy, value: showInsertedView)
}
}
演示视频中的完整示例在 FromMatchedGeometry.swift 中以 #Preview
的形式提供。