【问题标题】:Swift: Animating Constraints on UIImageViewSwift:UIImageView 上的动画约束
【发布时间】:2015-05-26 00:26:00
【问题描述】:

那里有几个回答的问题与我的相似,如果不一样的话,但是,它们似乎都没有解决我的困境。我有一个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定义为用户在superview中的位置

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

autolayout 有什么我失踪了吗?

要让image 以动画方式回到其原始位置,我需要进行哪些更改?

【问题讨论】:

  • 抱歉我的答案有误,我在这里做了快速研究和一些测试,我已经成功了,请再次查看我的答案,我会为你编辑。
  • 您更新的答案应该可以工作,但是,由于某种原因,似乎任何时候更改constraint 时,UIImageView 的位置都会在animation 之外更新。下面的@matt 答案对我有用。

标签: ios swift animation autolayout


【解决方案1】:

我还没有对此进行测试,但在这些情况下,我的第一个冲动总是尝试在延迟到主线程的情况下退出。所以,首先,将我给heredelay 实用程序粘贴到您的文件中(在import 之后但在其他所有内容之前)。现在用很短的延迟包装你的最后一个案例:

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

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

【讨论】:

  • 是的,这些是我在视图加载和存储原始 X 和 Y constraints 时设置的变量。一旦gesture 结束,我就会更新这些内容。
  • 你试过我说的了吗?
  • 刚试过。有效!了不起。知道引擎盖下发生了什么吗?
猜你喜欢
  • 1970-01-01
  • 2016-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
相关资源
最近更新 更多