简体   繁体   English

更改约束时`self.view.layoutIfNeeded()`做什么

[英]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? 我已经改编了如何使用Swift中的约束来动画UIView的代码

1. What does self.view.layoutIfNeeded() part of the code do? 1. self.view.layoutIfNeeded()代码的一部分是做什么的?

2. Why is it coded 2x, before and during animation? 2.为什么在动画之前和期间编码2x?

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. 注意:如果我注释掉第一个self.view.layoutIfNeeded()没有任何变化,但如果我注释掉第二个self.view.layoutIfNeeded()该动作不再是动画的,只会出现在新坐标中。

Essentially calling the self.view.layoutIfNeeded() will force the layout of self.view and its subviews if some change set setNeedsLayout for self.view . 基本上调用self.view.layoutIfNeeded()将强制self.view及其子视图的布局,如果某些更改为self.view设置setNeedsLayout

setNeedsLayout is used to set a flag that whenever layoutIfNeeded() is called, layoutSubviews will then be called. setNeedsLayout用于设置一个标志,每当调用layoutIfNeeded()时,都会调用layoutSubviews 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. 如果你对UIView进行了更改,导致它变为setNeedsLayout但是没有调用layoutIfNeeded() (因此不调用layoutSubviews),它将不会更新,因此可能会导致动画出现问题。 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. 当然,在制作动画时,您正在进行需要更新的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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