如何独立设置两个
.offset()
轴的动画?这看起来像一个错误,对吗?蓝色应该不断上下弹跳,但一旦我尝试为 y
偏移设置动画,x
动画就会停止。
@State var offsetX = 0.0
@State var offsetY = 0.0
var body: some View {
VStack {
Color.blue
.frame(width: 50, height: 50)
.offset(x: offsetX, y: offsetY)
.onAppear {
withAnimation(.easeInOut.repeatForever(autoreverses: true)) {
offsetY = 300
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
withAnimation {
offsetX = 100
}
}
}
}
}
听起来有点矫枉过正,但我做了一个自定义的 GeometryEffect,并且它独立动画:
extension View {
func independentOffset(x: CGFloat = 0, y: CGFloat = 0) -> some View {
modifier(OffsetGeometryEffect(offset: CGPoint(x: x, y: y)))
}
}
struct OffsetGeometryEffect: GeometryEffect {
var offset: CGPoint
var animatableData: CGPoint.AnimatableData {
get { CGPoint.AnimatableData(offset.x, offset.y) }
set { offset = CGPoint(x: newValue.first, y: newValue.second) }
}
func effectValue(size: CGSize) -> ProjectionTransform {
return ProjectionTransform(CGAffineTransform(translationX: offset.x, y: offset.y))
}
}