Search code examples
iosswiftxcodeanimationuiimageview

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


I have a code that creates a new UIImageView everytime a button is clicked and that UIImageView is then animated. However, whenever the button is clicked after it is clicked for the first time, I think the animation applied to the second UIImageView that is created affects the first UIImageView. In other words, both start to move very fast (much faster that programmed). This is my code:

@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)
})
}

I am relatively new with code and swift. Thanks in advance because I cannot quite seem to figure this out.


Solution

  • You should not try to do a whole bunch of chained animations every 0.00001 seconds. Most things on iOS have a time resolution of ≈ .02 seconds.

    You are trying to run an animation every 10 microseconds and move the image view 10 points each step. That comes to an animation of a million points per second. Don't do that.

    Just create a single animation that moves the image view to it's final destination over your desired time-span. The system will take care of pacing the animation for you. (Say you move it 100 pixels in 0.3 seconds. Just specify a duration of 0.3 seconds, and the body of the animation moves the image view by 100 pixels. There you go. It will just work.

    Note that your image views don't have any auto-layout constraints, so they will likely act strangely once the animation is complete.