user3582537
user3582537

Reputation: 424

Weird animation behavior using Swift 4 and UIView

I really can't figure out what's wrong with my code. Let me explain in detail what was my aim:

This is how I set the xCode project:

enter image description here

The behavior that I got is completely the opposite and I really can't understand why and what's happening:

enter image description here

Any tips or explanations for this?

Upvotes: 2

Views: 7831

Answers (1)

Michael Dautermann
Michael Dautermann

Reputation: 89549

Okay. Part of the problem is that you're aligning the center Y... which means that you're trying to break constraints with your animation.

Another part of the problem is that you are doing your animation in viewDidLoad, which totally runs before viewWillAppear and viewDidAppear get called.

For my own animations, I usually animate a constraint.

That is, get rid of the center-Y constraint for your red box and add a new constraint putting the red box some Y distance from the bottom of the superview. Connect this new constraint to an outlet and then you can animate like this:

@IBOutlet weak var redYConstraint : NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()
    // This line sets the red box to be in the center Y of the green box
    self.redYConstraint.constant = self.greenSquare.frame.midY
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    UIView.animate(withDuration: 3.0, delay: 2.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
        self.redYConstraint.constant = self.greenSquare.frame.maxY
        self.view.layoutIfNeeded()

    }, completion: nil)
}

Upvotes: 4

Related Questions