Search code examples
iosswiftcore-animation

Swift imageView animation doesn't work


I have code to create animation:

var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    imageView = UIImageView(frame:CGRect(x: 10, y: 10, width: 10, height: 10))
    imageView.image = UIImage(named:"2.png")

    UIView.animate(withDuration: 5) {

        self.imageView = UIImageView(frame:CGRect(x: 10, y: 10, width: 500, height: 500))

        self.view.addSubview(self.imageView)
        self.view.layoutIfNeeded()

        }
    }

But animation doesn't work. And imageView not showing.


Solution

  • There are things that makes sense within an animation block (here: UIView.animate). Creating a newer image view is not one of them. Neither is addSubView.

    The problem is that you are completely reassigning to your imageview variable - creating a new one within animation block.

    You should create your image view and add it to your main view completely before you execute UIView.animate.

    Animation is changing the visible properties of your objects, not recreating them. If you want frame change, simply do the following within animation block:

    self.imageView.frame = CGRect(x: 10, y: 10, width: 500, height: 500)
    

    You can also call layoutSubviews() or layoutIfNeeded() depending upon your constraint requirements, within UIView.animate.