具有自适应布局的 UIScrollView

UIScrollView with Adaptive Layout

我在 UIView 中有一个 UIScrollView,在滚动视图中有另一个 UIView(容器视图)。在自适应布局之前,我固定滚动视图以适应外部视图并设置容器视图的宽度和高度(也固定到滚动视图)。这样我就可以垂直滚动视图了。

现在,使用自适应布局后,由于屏幕尺寸不同,我无法设置宽度...我必须设置哪个约束?我能想到的唯一解决方案是以编程方式将宽度设置为屏幕大小...

来自UIScrollView and Autolayout

The UIScrollView class scrolls its content by changing the origin of its bounds. To make this work with Auto Layout, the top, left, bottom, and right edges within a scroll view now mean the edges of its content view.

The constraints on the subviews of the scroll view must result in a size to fill, which is then interpreted as the content size of the scroll view. (This should not be confused with the intrinsicContentSize method used for Auto Layout.) To size the scroll view’s frame with Auto Layout, constraints must either be explicit regarding the width and height of the scroll view, or the edges of the scroll view must be tied to views outside of its subtree.

在您的情况下,"Container View" 必须具有明确的大小,独立于滚动视图的大小。最简单的方法是添加高度和宽度约束,并将它们的 constant 属性 设置为您想要的值。

因此,如果您希望 "Container View" 成为屏幕的宽度,请添加宽度约束并将其常量设置为运行时的当前屏幕宽度。

将容器视图的宽度限制为等于根级视图的宽度。删除容器视图的硬编码宽度约束。