这是我希望您需要的示例,在move function
其中我添加了开始和结束位置更改状态逻辑。
我重命名并更新了位置类型,因为如果您在 View 函数中使用“位置”名称,swiftui 已经保留了它。var animate state
大多数时候不需要它,它的功能是禁用动画以在所需的动画偏移量上移动矩形,但只是在您想同时链接多个更改位置时出现,否则您可以将其删除。
您可以根据需要测试更改from
和to
值。
struct ExampleView: View {
@State var positionPoint: CGPoint = CGPoint.init(x: 0.5, y: 0.5)
@State var animate: Bool = false
var body: some View {
ZStack {
GeometryReader { geo in
Rectangle()
.fill(Color.red)
.frame(width: 200, height: 200)
.position(x: geo.size.width * positionPoint.x,
y: geo.size.height * positionPoint.y)
.animation(animate ? .easeIn : nil)
}
VStack(spacing: 10) { // some test button
Button(action: {
move(from: (0.2, 0.7), to: (0.8, 0.3))
}, label: {
Text("from: (0.2, 0.7), to: (0.8, 0.3)")
})
Button(action: {
move(from: (1, 1), to: (0.1, 0.1))
}, label: {
Text("from: (1, 1), to: (0.1, 0.1)")
})
Button(action: {
move(from: (0.6, 0.6), to: (0.5, 0.9))
}, label: {
Text("from: (0.6, 0.6), to: (0.5, 0.9)")
})
Button(action: {
move(from: (0.8, 0.1), to: (0.3, 1))
}, label: {
Text("from: (0.8, 0.1), to: (0.3, 1)")
})
}
}
}
func move(from: (CGFloat, CGFloat), to: (CGFloat, CGFloat)) {
animate = false
positionPoint = CGPoint.init(x: from.0, y: from.1)
withAnimation {
animate = true
positionPoint = CGPoint.init(x: to.0, y: to.1)
}
}
}