为什么我的matchedGeometryEffect动画以右下角而非中心点为锚点运动?
这个问题不是设备独有,是matchedGeometryEffect在跨位置条件渲染场景下的默认参数匹配异常导致的。
核心原因是系统插值计算时错误使用了右下角作为锚点,你只需要给两个矩形的matchedGeometryEffect修饰符补充显式的匹配属性和锚点参数即可。
修改后的代码如下:
import SwiftUI struct Test: View { @Namespace private var animation @State var show = false var body: some View { HStack { if !show { Rectangle() .frame(width: 50, height: 50) .matchedGeometryEffect(id: "animation", in: animation, properties: .frame, anchor: .center) } Spacer() Button(action: { withAnimation(.easeInOut) { show.toggle() } }) { Text("Switch") } Spacer() if show { Rectangle() .frame(width: 200, height: 200) .matchedGeometryEffect(id: "animation", in: animation, properties: .frame, anchor: .center) } } .padding() .frame(maxHeight: .infinity) } } struct Test_Previews: PreviewProvider { static var previews: some View { Test() } }
如果修改后仍有轻微偏移,可以给两个Rectangle都添加.transition(.identity),禁用系统默认的透明度过渡,完全交给matchedGeometryEffect接管动画逻辑即可。
内容的提问来源于stack exchange,提问作者2nebin
相关产品推荐
相关产品推荐

