在自动布局中
通常,自动布局将视图的顶部、左侧、底部和右侧边缘视为可见边缘。也就是说,如果您将视图固定到其父视图的左边缘,您实际上是将其固定到父视图边界的最小 x 值。更改超级视图的边界原点不会更改视图的位置。
UIScrollView 类通过更改其边界的原点来滚动其内容。为了使用自动布局,滚动视图中的顶部、左侧、底部和右侧边缘现在意味着其内容视图的边缘。
对滚动视图的子视图的约束必须导致要填充的大小,然后将其解释为滚动视图的内容大小。 (这不应与用于 Auto Layout 的 intrinsicContentSize 方法混淆。)要使用 Auto Layout 调整滚动视图的框架大小,必须明确限制滚动视图的宽度和高度,或者滚动视图的边缘必须是绑定到其子树之外的视图。
请注意,您可以通过在视图和滚动视图的子树之外的视图(例如滚动视图的超级视图)之间创建约束,使滚动视图的子视图看起来浮动(不滚动)在其他滚动内容之上。
这里有两个如何配置滚动视图的例子,首先是混合方式,然后是纯方式
混合方法
使用滚动视图外部的约束来定位和调整滚动视图的大小,即 translatesAutoresizingMaskIntoConstraints 属性设置为 NO。
为您的滚动视图创建一个普通的 UIView 内容视图,该视图将是您希望内容具有的大小。使其成为滚动视图的子视图,但让它继续将自动调整大小的掩码转换为约束:
- (void)viewDidLoad {
UIView *contentView;
contentView = [[UIView alloc] initWithFrame:CGRectMake(0,0,contentWidth,contentHeight)];
[scrollView addSubview:contentView];
// 不要改变 contentView 的 translatesAutoresizingMaskIntoConstraints,
//默认是YES;
// 设置滚动视图的内容大小以匹配内容视图的大小:
[scrollView setContentSize:CGSizeMake(contentWidth,contentHeight)];
/* 其余代码在这里... */
}
创建要放入内容视图中的视图并配置它们的约束,以便将它们定位在内容视图中。
或者,您可以创建一个视图子树以进入滚动视图,设置您的约束,并调用 systemLayoutSizeFittingSize: 方法(使用 UILayoutFittingCompressedSize 选项)来查找您想要用于内容视图的大小和 contentSize滚动视图的属性
纯自动布局方法
要使用纯自动布局方法,请执行以下操作:
在所有涉及的视图上将 translatesAutoresizingMaskIntoConstraints 设置为 NO。
使用滚动视图外部的约束来定位和调整滚动视图的大小。
使用约束在滚动视图中布置子视图,确保约束绑定到滚动视图的所有四个边缘,并且不依赖滚动视图来获取它们的大小。
一个简单的例子是一个大图像视图,它具有从图像大小派生的内在内容大小。在视图控制器的 viewDidLoad 方法中,您将包含类似于以下清单中所示代码的代码:
- (void)viewDidLoad {
UIScrollView *scrollView;
UIImageView *imageView;
NSDictionary *viewsDictionary;
// Create the scroll view and the image view.
scrollView = [[UIScrollView alloc] init];
imageView = [[UIImageView alloc] init];
// Add an image to the image view.
[imageView setImage:[UIImage imageNamed:"MyReallyBigImage"]];
// Add the scroll view to our view.
[self.view addSubview:scrollView];
// Add the image view to the scroll view.
[scrollView addSubview:imageView];
// Set the translatesAutoresizingMaskIntoConstraints to NO so that the views autoresizing mask is not translated into auto layout constraints.
scrollView.translatesAutoresizingMaskIntoConstraints = NO;
imageView.translatesAutoresizingMaskIntoConstraints = NO;
// Set the constraints for the scroll view and the image view.
viewsDictionary = NSDictionaryOfVariableBindings(scrollView, imageView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|" options:0 metrics: 0 views:viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|" options:0 metrics: 0 views:viewsDictionary]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[imageView]|" options:0 metrics: 0 views:viewsDictionary]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[imageView]|" options:0 metrics: 0 views:viewsDictionary]];
/* the rest of your code here... */
}