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

标签 ios swift

所以我正在学习如何使屏幕外的 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/

相关文章:

objective-c - ->运算符在-copyWithZone:中做什么?

iphone - Xcode 无法识别 iPhone 5s,dyld_shared_cache_extract_dylibs 失败

ios - NSAttributedString 如何遵循 MVC 范式?

ios - 键盘在桌面 View 交互上消除了很多错误

html - 如何让 webview 只加载特定的网站,比如 youtube?

iphone - 如何使用swift在游戏中心报告高分

arrays - 涉及数组和具有数组成员的对象的复杂过滤

ios - ID 为 xxxxxxxx 的应用程序在 id 为 yyyy 的应用程序上没有正确的 view_struct

ios - 如何自动缩放 mapView 以显示覆盖

ios - 单元格高度可变的 UITableView : Working in IB but not programmatically