16

So I'm learning how to make views animate from out of screen, to use as slider-menus.

class ViewController: UIViewController {
    @IBOutlet weak var red: UIView!
    @IBOutlet weak var redHConstraint: NSLayoutConstraint!

    @IBAction func buttonShift(sender: AnyObject) {
        self.view.layoutIfNeeded()        // **HERE**
        UIView.animateWithDuration(0.5) {
            self.redHConstraint.constant = 0
            self.view.layoutIfNeeded()    // And **HERE**
        }
    }

}

i've adapted this code from How to animate a UIView with constraints in Swift?

1. What does self.view.layoutIfNeeded() part of the code do?

2. Why is it coded 2x, before and during animation?

Note: if i comment-out the 1st self.view.layoutIfNeeded() nothing changes, but if i comment-out the 2nd self.view.layoutIfNeeded() the movement is no longer animated and just appears in the new coordinates.

Meet Doshi
  • 4,241
  • 10
  • 40
  • 81
Chameleon
  • 1,608
  • 3
  • 21
  • 39

1 Answers1

31

Essentially calling the self.view.layoutIfNeeded() will force the layout of self.view and its subviews if some change set setNeedsLayout for self.view.

setNeedsLayout is used to set a flag that whenever layoutIfNeeded() is called, layoutSubviews will then be called. It is what determines the "if needed" aspect of the call.

If you make a change to UIView which causes it to setNeedsLayout but layoutIfNeeded() is not called (therefore layoutSubviews is not called) it will not update and therefore could cause issues with your animation. If you call it before hand it will ensure that if there was a change that needed your layout to be updated then it will apply it to your view and all of its subviews before animating.

And of course, when animating you are making changes which need to be updated.

chrissukhram
  • 2,957
  • 1
  • 13
  • 13
  • so 1st makes sure all `objects` in `red:UIView` are in place? so if I comment out 1st one all the stuff in `red` will be mixed up? – Chameleon Mar 19 '15 at 17:38
  • If you comment it out, there is a possibility that if some action caused self.view to change and "setNeedsLayout" but self.view.layoutIfNeeded() was not called it would not update and therefore could mess up your animation. – chrissukhram Mar 19 '15 at 17:39
  • @chrissukhram, thanks for the explanation. Once this animation of constraints starts, how do I pause/stop it? I have tried .removeAllAnimations() which does stop it but also jumps to the end of the animation. I've also tried starting another animation with a very short duration with options: UIViewAnimationOptions.BeginFromCurrentState set (as suggested elsewhere in SO) but that does not stop the animation at all. Thx – rockhammer Aug 06 '16 at 01:42