繁体   English   中英

如何为单击按钮时以编程方式创建的 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 的 animation 会影响第一个 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 上的大多数东西的时间分辨率约为 0.02 秒。

您正在尝试每 10 微秒运行一次 animation 并将图像视图每一步移动 10 个点。 这相当于每秒一百万点的 animation。 不要那样做

只需创建一个 animation 即可在所需的时间跨度内将图像视图移动到最终目的地。 系统将为您处理 animation 的起搏。 (假设您在 0.3 秒内将其移动 100 个像素。只需指定 0.3 秒的持续时间,animation 的主体将图像视图移动 100 个像素。go 就可以了。

请注意,您的图像视图没有任何自动布局约束,因此一旦 animation 完成,它们可能会出现奇怪的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM