layoutIfNeeded 是如何使用的?

How is layoutIfNeeded used?(layoutIfNeeded 是如何使用的?)

本文介绍了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:

  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 是如何使用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:layoutIfNeeded 是如何使用的?

基础教程推荐