使用 viewDidLayoutSubviews 时出现问题

Issue while using viewDidLayoutSubviews

我听说 viewDidLayoutSubviews 是我们使用约束后更改布局的最佳位置。

所以我跳到viewDidLayoutSubviews

我在 SuperView 上创建了三个 UIViewsSubViewed。帧计算的代码我就不说了

 [self.view addSubview:imgMiddleCircle];
 [self.view addSubview:imgFirstCircle];
 [self.view addSubview:imgLastCircle]; 

使用这块我正在添加这些圈子。

现在,当我 运行 我的代码在 viewDidLayoutSubviews 中时,我得到以下屏幕:

当我切换到 viewWillLayoutSubviews 时,我在屏幕上看到了这个:

为什么我在 viewDidLayoutSubviews 中得到了额外的两个圆圈,即使我创建了三个圆圈。

以及为什么 viewWillLayout 给出了正确的输出。

根据 Apple Documentation

When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls this method. However, this method being called does not indicate that the individual layouts of the view's subviews have been adjusted. Each subview is responsible for adjusting its own layout.

Your view controller can override this method to make changes after the view lays out its subviews. The default implementation of this method does nothing.

因此,从本质上讲,viewDidLayoutSubiews 在创建 viewController 期间会被多次调用,包括在旋转设备、滚动等情况下。因此,您应该非常小心自己编写的代码添加到此方法,因为它也可能会执行多次。 使用此方法重新定位您的子视图,而不是 add/remove 它们。

查看此blog了解更多详情。

您应该针对 viewDidLayoutSubviews 被称为多种类型这一事实编写代码。

理想情况下 addSubview: 应该发生在像 viewDidLoad 这样的地方,您确定它只被调用一次。

您可以创建一个标志以避免调用 addSubview: 多个类型(不是我个人的选择)

否则,请尝试将您的设置代码移动到 viewDidLoad 并强制视图在进行计算之前自行呈现:

[yourView setNeedsLayout];

[yourView layoutIfNeeded];