How is layoutIfNeeded used?(layoutIfNeeded 是如何使用的?)
问题描述
layoutIfNeeded
何时以及如何使用?我知道当我们更改视图的布局时,我们可以调用 setNeedsLayout
来更新布局,但不确定何时应该使用 layoutIfNeeded
.
When and how is layoutIfNeeded
used? I know that when we change the layout of a view, we can call setNeedsLayout
to update the layout but not sure when layoutIfNeeded
should be used.
注意:我在实际代码中使用了 layoutIfNeeded
,但忘记了它是在什么上下文中使用的.
NOTE: I have layoutIfNeeded
used in actual code but forgot in what context it was used.
推荐答案
layoutIfNeeded
强制接收器在需要时立即布局其子视图.
layoutIfNeeded
forces the receiver to layout its subviews immediately if required.
假设你已经覆盖了 layoutSubviews
,并且 UIKit 认为你的视图出于任何原因需要布局(例如,你在处理某些用户操作时调用了 setNeedsLayout
).然后,您的自定义 layoutSubviews
方法将立即被调用,而不是在常规 UIKit 运行循环事件序列中通常调用它时(在事件处理之后,但在 drawRect:
之前).
Suppose you have overridden layoutSubviews
, and UIKit feels that your view requires layout for whatever reason (e.g. you called setNeedsLayout
when handling some user action). Then, your custom layoutSubviews
method will be called immediately instead of when it would normally be called in the regular UIKit run loop event sequence (after event handling, but before drawRect:
).
您可能需要在单个运行循环中调用 layoutIfNeeded
的示例:
An example of why you might need to call layoutIfNeeded
within a single run loop:
- 您调整包含具有自定义布局的表格视图的自定义视图的大小.
setNeedsLayout
已设置,以便稍后调用layoutSubviews
. - 控制器对象在处理用户事件时要求表格视图滚动到某个特定单元格.
- 您的自定义视图对
layoutSubviews
中的表格视图执行一些自定义大小调整,从而更改表格视图的大小.
- You resize a custom view containing a table view with a custom layout.
setNeedsLayout
is set so thatlayoutSubviews
will be called later. - A controller object asks the table view to scroll to some particular cell when handling a user event.
- Your custom view performs some custom sizing of the table view in
layoutSubviews
that changes the table view size.
问题是当控制器要求表格视图滚动时(第 2 步),表格视图的边界已经过时.更新的边界稍后将仅在表视图上设置(步骤 3).layoutSubviews
完成后,控制器希望表格视图滚动到的内容实际上可能不可见.一个解决方案是控制器在知道这可能发生的情况下调用 layoutIfNeeded
.
The problem is when the controller asked the table view to scroll (step 2), the table view had bounds that were stale. The updated bounds would only be set on the table view later (step 3). What the controller wanted the table view to scroll to may not actually be visible after layoutSubviews
is done. A solution then would be for the controller to call layoutIfNeeded
in situations where it knows this might occur.
这篇关于layoutIfNeeded 是如何使用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:layoutIfNeeded 是如何使用的?
基础教程推荐
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01