如何为在单击按钮时以编程方式创建的 UIImageView 设置动画? (每次单击按钮都会创建一个具有相同图像的新 UIImageView)

How do I animate a UIImageView that was created programatically upon button click? (Each button click creates a new UIImageView with the same image)

我有一个代码,每次单击按钮时都会创建一个新的 UIImageView,然后为该 UIImageView 设置动画。但是,每当第一次单击按钮后单击该按钮时,我认为应用于创建的第二个 UIImageView 的动画会影响第一个 UIImageView。换句话说,两者都开始非常快速地移动(比编程快得多)。这是我的代码:

@IBAction func buttonClicked(_ sender: Any) {
var imageName: String = "ImageName"
var image = UIImage(named: imageName)
var imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0,y: 0,width: 50,height: 50)
view.addSubView(imageView)
moveIt(imageView)
}

func moveIt(_ imageView: UIImageView) {
UIView.animate(withDuration:TimeInterval(0.00001), delay: 0.0, options: .curveLinear, animations: {
imageView.center.x+=3
}, completion: {(_) in self.moveIt(imageView)
})
}

我对代码和 swift 比较陌生。提前致谢,因为我似乎不太明白这一点。

您不应该尝试每 0.00001 秒执行一大堆链接动画。 iOS 上的大多数内容的时间分辨率为 ≈ .02 秒。

您正在尝试每 10 微秒 运行 一个动画,并且每一步将图像视图移动 10 点。这就涉及到每秒一百万点的动画。 不要那样做

只需创建一个动画,将图像视图移动到您想要的最终目的地 time-span。系统会为您调整动画的节奏。 (假设你在 0.3 秒内将它移动 100 像素。只需指定 0.3 秒的持续时间,动画主体将图像视图移动 100 像素。就这样。它会正常工作。

请注意,您的图像视图没有任何 auto-layout 约束,因此一旦动画完成,它们可能会表现得很奇怪。