来自 Apple 开发人员关于 Auto Layout Guide 的部分名称“Working with Scroll Views”为您的问题提供了明确的解决方案
对于大多数常见的布局任务,如果您使用
包含滚动视图内容的虚拟视图或布局组。
在 Interface Builder 中工作时,显示了一般方法
下面:
- 将滚动视图添加到场景中。
- 绘制约束来定义
像往常一样滚动视图的大小和位置。
- 为滚动添加视图
看法。将视图的 Xcode 特定标签设置为 Content View。
- 将内容视图的顶部、底部、前导和后沿固定到滚动条
视图的对应边。内容视图现在定义了滚动
视图的内容区域。
- (可选)要禁用水平滚动,请将内容视图的宽度设置为等于滚动视图的宽度。内容视图现在水平填充滚动视图。
- (可选)要禁用垂直滚动,请将内容视图的高度设置为等于滚动视图的高度。内容视图现在水平填充滚动视图。
- 在内容视图中布置滚动视图的内容。使用约束在内容视图中正常定位内容。
通过代码进行自动布局的另一件重要的事情是
通过此代码禁用从自动调整大小掩码到约束的转换:
scrollView.translatesAutoresizingMaskIntoConstraints = false;
viewA.translatesAutoresizingMaskIntoConstraints = false;
viewB.translatesAutoresizingMaskIntoConstraints = false;
所以你的视图层次结构是:
-view
-scrollView
-scrollContentView
-view A
-view B
scrollView 的约束类似于普通视图,例如,您希望 scrollView 占据其父视图中的所有空间。
[scrollView.leadingAnchor constraintEqualToAnchor:view.leadingAnchor];
[scrollView.trailingAnchor constraintEqualToAnchor:view.trailingAnchor];
[scrollView.topAnchor constraintEqualToAnchor:view.topAnchor];
[scrollView.bottomAnchor constraintEqualToAnchor:view.bottomAnchor];
和scrollContentView类似
[scrollContentView.leadingAnchor constraintEqualToAnchor: scrollView.leadingAnchor];
[scrollContentView.trailingAnchor constraintEqualToAnchor: scrollView.trailingAnchor];
[scrollContentView.topAnchor constraintEqualToAnchor: scrollView.topAnchor];
[scrollContentView.bottomAnchor constraintEqualToAnchor: scrollView.bottomAnchor];
最后是viewA和viewB的约束,将viewA的底部引脚设置为viewB的顶部
[viewA.leadingAnchor constraintEqualToAnchor: scrollContentView.leadingAnchor];
[viewA.trailingAnchor constraintEqualToAnchor: scrollContentView.trailingAnchor];
[viewA.topAnchor constraintEqualToAnchor: scrollContentView.topAnchor];
[viewA.bottomAnchor constraintEqualToAnchor: viewB.topAnchor];
[viewB.leadingAnchor constraintEqualToAnchor: scrollContentView.leadingAnchor];
[viewB.trailingAnchor constraintEqualToAnchor: scrollContentView.trailingAnchor];
[viewB.topAnchor constraintEqualToAnchor: viewA.bottomAnchor];
[viewB.bottomAnchor constraintEqualToAnchor: scrollContentView.topAnchor];