简体   繁体   中英

What does `self.view.layoutIfNeeded()` do when changing constraints

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM