0
votes

I have 4 buttons, all use the same animate func

  • imageViewWithoutDelay
  • imageViewWithDelay
  • ViewWithoutDelay
  • ViewWithDelay

my code:

import UIKit

class ViewController: UIViewController {

    @IBAction func imageViewithoutDelay(_ sender: AnyObject) {
        let circleImage = UIImageView()
        // kindly add your own image.
        circleImage.image = UIImage(named: "empty")
        animate(inputView: circleImage, delay: false)
    }

    @IBAction func imageViewWithDelay(_ sender: UIButton) {

        let circleImage = UIImageView()
        circleImage.image = UIImage(named: "empty")
        animate(inputView: circleImage, delay: true)
    }

    func animate(inputView : UIView, delay: Bool){

        inputView.layer.cornerRadius = inputView.frame.size.width / 2
        inputView.clipsToBounds = true
        inputView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(inputView)

        let screenSize = UIScreen.main.bounds
        let screenHeight = screenSize.height * 0.10
        inputView.center.y = screenHeight
        view.setNeedsLayout()
        view.setNeedsDisplay()

        if delay == true{
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
            UIView.animate(withDuration: 2.5, animations: {
                inputView.alpha = 0.0
                let screenSize = UIScreen.main.bounds
                let screenHeight = screenSize.height * 0.10
                inputView.center.y -= screenHeight
            })
        })} else{
            UIView.animate(withDuration: 2.5, animations: {
                inputView.alpha = 0.0
                let screenSize = UIScreen.main.bounds
                let screenHeight = screenSize.height * 0.10
                inputView.center.y -= screenHeight
            })

        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

}

What amuses me is the different behavior of the UIview & UIImageView.

The UIImageView instance only animates as intended (going up from origin) if I use delay. However, without using a delay block, UIImageView instance first drops down, then animates going up to its origin).

The UIView doesn’t show different behaviors. It animates from its origin and goes up.

enter image description here Is this a bug?

This question is a tangent to this original question.

1

1 Answers

1
votes

What you're doing is wrong no matter how you slice it. You cannot add a view and animate it all in the same breath. You can only animate a view that is already in the interface.

That is why it works for the image view if you add the delay: by the time you animate, the image view has gotten into the interface and the interface has settled down.

The fact that it seems to work for the non-imageview is just dumb luck.