gpt4 book ai didi

ios - 改变约束时 `self.view.layoutIfNeeded()`做什么

转载 作者:IT王子 更新时间:2023-10-29 05:20:50 31 4
gpt4 key购买 nike

所以我正在学习如何使屏幕外的 View 具有动画效果,以用作 slider 菜单。

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**
}
}

}

我从 How to animate a UIView with constraints in Swift? 改编了这段代码

<强>1。 self.view.layoutIfNeeded() 部分代码的作用是什么?

<强>2。为什么在动画之前和期间编码为 2x?

注意:如果我注释掉第一个 self.view.layoutIfNeeded() 没有任何变化,但是如果我注释掉第二个 self.view.layoutIfNeeded() 运动不再是动画的,只是出现在新的坐标中。

最佳答案

本质上调用 self.view.layoutIfNeeded() 将强制 self.view 及其 subview 的布局,如果某些更改集 setNeedsLayout对于 self.view

setNeedsLayout 用于设置一个标志,每当调用 layoutIfNeeded() 时,就会调用 layoutSubviews。它决定了调用的“如果需要”方面。

如果您对 UIView 进行了更改,导致它 setNeedsLayout 但未调用 layoutIfNeeded()(因此未调用 layoutSubviews),它不会更新,因此可能导致你的动画出现问题。如果您事先调用它,它将确保如果有需要更新布局的更改,那么它会在动画之前将其应用于您的 View 及其所有 subview 。

当然,在制作动画时,您正在做出需要更新的更改。

关于ios - 改变约束时 `self.view.layoutIfNeeded()`做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29151204/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com