UIView.animateWithDuration: 动画总是停在原来的位置

UIView.animateWithDuration: animation always stops at original position

我在视图中间添加了一个 ImageView(未设置约束)。

使用此代码,我想将此 ImageView 从其原始位置移动到新位置。

不幸的是,它从新位置移到了原来的位置 - 为什么?

let opts = UIViewAnimationOptions.CurveEaseInOut
UIView.animateWithDuration(1, delay: 0, options: opts, animations: {
     self.ivSun.center.x += 100
}, completion: nil) 

动画完成后添加。

self.ivSun.layer.position = self.ivSun.layer.presentationLayer().position

我有在我的游戏中实现的代码。

        CATransaction.begin()
        CATransaction.setCompletionBlock { () -> Void in
                    self.viewBall.layer.position = self.viewBall.layer.presentationLayer().position
            }
        }
        var animation = CABasicAnimation(keyPath: "position")
        animation.duration = ballMoveTime
        animation.fromValue = NSValue(CGPoint: viewBall.layer.presentationLayer().position)
        animation.toValue = NSValue(CGPoint: CGPointMake(self.borderRight, self.borderMiddle))
        animation.removedOnCompletion = false
        animation.fillMode = kCAFillModeForwards
        viewBall.layer.addAnimation(animation, forKey: "transform")
        CATransaction.commit()

根据需要更改位置值。

试试这个。

func animateImage()
{
    UIView.animateWithDuration(3.0, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
        self.imageView.center = CGPointMake(self.imageView.center.x+10, self.imageView.center.y+10)
    }, completion: nil)
}

在不了解上下文和相关代码的情况下,很难给出答案 "why" 它正在快速回到原来的位置,但作为替代方案,您可以根据需要设置完成处理程序作为最后的 position/coordinate.

一般来说,我在我的 widgets/views 上使用约束,并且我对它们的值进行动画处理(例如,与对小部件的框架进行动画处理相比)......效果非常好。

这是由于自动布局。需要在动画中更改和更新约束,如下所示:

- (IBAction)moveAction:(id)sender {
    self.spaceConstraint.constant += 220;

    [UIView animateWithDuration:0.5 animations:^{
         [self.imageView layoutIfNeeded];
    }];
}
var animation = CABasicAnimation(keyPath: "position")
animation.duration = ballMoveTime
animation.fromValue = NSValue(CGPoint: viewBall.layer.presentationLayer().position)
animation.toValue = NSValue(CGPoint: CGPointMake(self.borderRight, self.borderMiddle))
animation.removedOnCompletion = false
animation.fillMode = kCAFillModeForwards
viewBall.layer.addAnimation(animation, forKey: "transform")
CATransaction.commit()