ios – Add UIView and animate it instantly


I am including a UIView to a view controller and wish to it render after which instantly animate its motion, however an odd issues is occurring. The brand new view is being drawn on the vacation spot the place I wish to animate it to after which animating to the origin that I had set it at. So it is primarily taking place in reverse. This is my code:

class ViewController: UIViewController {

    override func viewDidLoad() {
        tremendous.viewDidLoad()
        // Do any extra setup after loading the view.
    }
    
    @IBAction func buttonTapped(_ sender: Any) {
        let sq. = UIView()
        sq..backgroundColor = .crimson
        sq..translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(sq.)
        [square.widthAnchor.constraint(equalToConstant: 100),
         square.heightAnchor.constraint(equalToConstant: 100),
         square.centerXAnchor.constraint(equalTo: view.centerXAnchor),
         square.centerYAnchor.constraint(equalTo: view.centerYAnchor)].forEach { $0.isActive = true }
        UIView.animate(withDuration: 2.0) {
            var frameCopy = sq..body
            frameCopy.origin.y -= 300
            sq..body = frameCopy
        }
    }

}

If I remark out the UIView.animate that is what will get created after I press the button, and that is what I count on

enter image description here

However then if I add the animation again in, that is what occurs:

enter image description here

In order you may see the origin begins -300 off centre after which strikes to the centre whereas I wish to to start out on centre after which transfer -300 off the display screen. Can anybody assist with this?

For the work I am doing I want so as to add the view after which animate it instantly, I can not add the view beforehand and animate it later.

Leave a Reply