gpt4 book ai didi

ios - Swift:UIImageView 上的动画约束

转载 作者:可可西里 更新时间:2023-11-01 01:40:09 25 4
gpt4 key购买 nike

有几个已回答的问题与我的问题即使不一样也很相似,但是,它们似乎都无法解决我的难题。我有一个 UIImageView,我使用 UILongPressGesture 在屏幕上移动,我通过更改水平和垂直 constraints 来移动它。如果此 image 没有移动一定距离,我希望它通过动画回到原来的位置。我正在使用以下是我用来尝试执行此操作的代码示例:

if sender.state == UIGestureRecognizerState.Changed {

image1ConstraintX.constant = imageConstX + (translation.x - location.x)
image1ConstraintY.constant = imageConstY + (translation.y - location.y)

} else if sender.state == UIGestureRecognizerState.Ended {

var xPosition = self.image1.frame.origin.x + image1.frame.width/2
var yPosition = self.image1.frame.origin.y + image1.frame.width/2
imageConstX = image1ConstraintX.constant
imageConstY = image1ConstraintY.constant

if xPosition < 215 && yPosition < 210 {
self.image1ConstraintX.constant = 13
self.image1ConstraintY.constant = 17
UIView.animateWithDuration(1.3, delay: 0.0, options: nil, animations: {
self.view.layoutIfNeeded()

}, completion: nil)
}

location.xlocation.y 在别处定义为用户点击的位置

translation.xtranslation.y 定义为用户在父 View 中的位置

不用说,平移 image 时一切正常。它拖动,然后在手势结束时停止。问题是,如果用户不将 image 拖过某个位置,我希望 image 动画回到其原始位置,而不是平滑过渡,它立即回到原来的位置,根本没有动画。根据对类似问题的其他答案,我正在设置约束,然后在 animateWithDuration 中调用 layoutIfNeeded

autolayout 是不是我遗漏了什么?

要使 image 动画回到其原始位置,我需要更改什么?

最佳答案

我没有对此进行测试,但在这些情况下,我的第一个冲动总是尝试延迟到主线程。因此,首先,将我提供的 delay 实用程序粘贴到您的文件中(在 import 之后但在其他所有内容之前) here .现在在非常短的延迟内结束您的最终案例:

if xPosition < 215 && yPosition < 210 {
delay(0.1) {
self.image1ConstraintX.constant = 13
self.image1ConstraintY.constant = 17
UIView.animateWithDuration(1.3, delay: 0.0, options: nil, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}

如果那不能解决问题,那么我的下一步行动就是考虑这些行:

imageConstX = image1ConstraintX.constant
imageConstY = image1ConstraintY.constant

那些不是局部变量,那么它们是什么?也许设置它们会产生您没有考虑到的副作用。

关于ios - Swift:UIImageView 上的动画约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30447645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com