gpt4 book ai didi

ios - 使用 setNeedsLayout 动画约束变化

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:28:24 25 4
gpt4 key购买 nike

动画约束变化的标准方法是。

// Change constraints like:
someConstraint.constant = 100

UIView.animate(withDuration: 0.25) {
view.layoutIfNeeded()
}

但是我在看WWDC 2015 session on multitasking on iPad and at the end它说不要在动画 block 中使用 layoutIfNeeded,而是使用 setNeedsLayout。但是我一直认为这意味着布局发生在运行循环的后面,因此发生在动画 block 之外。也许它记得它是在动画 block 中调用的?

我尝试在我的代码中将 layoutIfNeeded 替换为 setNeedsLayout,它似乎有效。这只是巧合吗?我们实际上应该使用 setNeedsLayout 为自动布局更改设置动画吗?

Slide from WWDC video showing to use setNeedsLayout instead

最佳答案

layoutIfNeeded() 的文档指出:

Use this method to force the view to update its layout immediately. When using Auto Layout, the layout engine updates the position of views as needed to satisfy changes in constraints. Using the view that receives the message as the root view, this method lays out the view subtree starting at the root. If no layout updates are pending, this method exits without modifying the layout or calling any layout-related callbacks.

setNeedsLayout() 的文档指出:

Call this method on your application’s main thread when you want to adjust the layout of a view’s subviews. This method makes a note of the request and returns immediately. Because this method does not force an immediate update, but instead waits for the next update cycle, you can use it to invalidate the layout of multiple views before any of those views are updated. This behavior allows you to consolidate all of your layout updates to one update cycle, which is usually better for performance.

setNeedsLayout() 将 View 的所有 subview 的布局推迟到运行循环的下一个周期,从而将所有更改合并到适当的时间,而不是回避过程并强制执行布局瞬间发生。是的,您应该在 UIView.animate 函数中使用 setNeedsLayout() 而不是 layoutIfNeeded()。尽可能做一个好公民。

关于ios - 使用 setNeedsLayout 动画约束变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54746106/

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