使具有动态高度子视图的 UIScrollView 自动与自动布局一起工作

Make UIScrollView with dynamic height subviews work automatically with Auto Layout

我有以下视图结构及其约束:

UIView "parent"
   UIScrollView (leading, trailing, top and bottom to superview)
      - UIView "container" (leading, trailing, top and bottom to UIScrollView, 
                            equal width and height so parent UIView)
         - UIView "A" (leading, trailing, top to UIScrollView, height of 200)
         - UIView "B" (top, leading and trailing to UIView A, height of 140)
         - UIView "C" (top, leading and trailing to UIView B, height >= 88 "rest
                       of the screen until bottom", bottom to UIView "container")

"A" 和 "B" UIView 不会更改其大小,但 "C" 会。在其中,我以编程方式添加 n "labels containers" UIView ,它们具有不同的高度,具体取决于 m UILabel 他们主办。

现在,我正在计算 n UILabelboundingRectWithSize: 的大小,并且我正在调整其父项 [=63= 的高度] UIView 它被添加到 "C" UIView 中,将其高度限制设置为所有 UILabel.

的总和

然后,我调整 "C" UIView 高度约束,使其等于所有添加的 UIView.

的总和

这在所有不同的屏幕尺寸、纵向和横向上都能完美运行。 UIScrollView 显示所有三个 "A"、"B" 和 "C" 子视图,具有 "C" n UIView 主机 m UILabel.

但现在我在旋转设备时遇到了麻烦。我面临的问题是我必须重新计算所有 UILabel 的大小以更改所有 "labels container" UIView 的高度约束并更改 "C" UIView 高度约束,以便它可以适应所有视图之间没有大空白的所有内容。

所以我的问题是:我怎样才能完全使用 Auto Layout 来实现相同的行为?

现在我必须重新计算大小并更改高度限制,以便一切都适应,但我希望所有 UILabel 自动调整自己的大小并适合其内容,然后 "labels container" UIView 调整大小以适合所有 UILabel 然后 "C" UIView 自动调整大小以适合内容。

提前致谢!

据我所知,您需要为 动态标签 添加 TableView,为此您必须执行以下步骤:

1step : 添加 ScrollView 在你的 ViewController.

2步:在ScrollView中添加ContainerView来管理滚动constrains.

3step : 添加固定大小的“A”视图,比如说 150px。

4step : 添加固定大小的“B”视图,比如说 150px。

5step : 为固定大小为 0px 的动态标签添加 TableView。在此步骤中,将您的 tableView 高度设为 Outlet Constrains 我们将在下一步中使用它。

6step : 致电您的服务并在 tableView.

中添加标签

第 6 步骤中,当您在 table 视图中添加标签时,意味着当您重新加载 tableView 时,请执行以下操作 动态高度约束代码.

7step : 现在根据您的行高调整 table 视图的高度,如下所述。

arrListArray = @[@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven",@"Eight",@"Nine",@"Ten"];
int rowHeight = 44;
self.tblHeightConstraint.constant = (rowHeight * arrListArray.count);

现在使用以下方法重新加载您的约束:

[UIView animateWithDuration:0.1
                     animations:^{
                         // Called on parent view
                         [self.view layoutIfNeeded];
}];

它会自动增加你的 scrollView 包含大小。

显示示例图片:

查看约束堆栈:

现在根据您的评论,您必须添加 CollectionView 代替 tableView,并根据您的具体设计在 CollectionViewCell 中添加 TableView

希望这对您有所帮助!

好的,我做错了三件事:

1st: 我正在计算要设置的标签的高度,然后使用高度约束来设置 "labels container" UIView 的大小。不需要高度限制,因为 Auto Layout 管理一切。

2nd: 我正在通过添加高度值手动修改 "C" UIView 约束高度每个 "labels container" UIView 添加。

3rd: 修复了前两步后,我忘记设置最后添加的 UIView 约束及其父视图...

现在一切正常。