layoutIfNeeded是如何使用的? [英] How is layoutIfNeeded used?

查看:278
本文介绍了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运行循环事件序列中调用它(在事件处理之后但在<$ c $之前) c> 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:


  1. 您可以调整包含具有自定义布局的表视图的自定义视图的大小。设置了 setNeedsLayout ,以便稍后调用 layoutSubviews

  2. 控制器对象要求表视图在处理用户事件时滚动到某个特定单元格。

  3. 您的自定义视图在 layoutSubviews 更改表视图大小。

  1. You resize a custom view containing a table view with a custom layout. setNeedsLayout is set so that layoutSubviews will be called later.
  2. A controller object asks the table view to scroll to some particular cell when handling a user event.
  3. 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是如何使用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆