滚动视图的约束与其他视图的约束略有不同。contentViewof和 its superview(the scrollView)之间的约束是针对scrollView's 的contentSize,而不是针对 its 的frame。这可能看起来令人困惑,但实际上非常有用,这意味着您无需调整contentSize,而是contentSize会自动调整以适应您的内容。此行为在技术说明 TN2154中进行了描述。
例如,如果你想定义contentView屏幕的大小或类似的东西,你必须contentView在主视图和主视图之间添加一个约束。诚然,这与将内容放入滚动视图是对立的,所以我可能不建议这样做,但可以做到。
为了说明这个概念, 的大小contentView将由其内容驱动,而不是由 的bounds,在scrollView您的 中添加一个标签contentView:
UIScrollView* scrollView = [UIScrollView new];
scrollView.translatesAutoresizingMaskIntoConstraints = NO;
scrollView.backgroundColor = [UIColor redColor];
[self.view addSubview:scrollView];
UIView* contentView = [UIView new];
contentView.translatesAutoresizingMaskIntoConstraints = NO;
contentView.backgroundColor = [UIColor greenColor];
[scrollView addSubview:contentView];
UILabel *randomLabel = [[UILabel alloc] init];
randomLabel.text = @"this is a test";
randomLabel.translatesAutoresizingMaskIntoConstraints = NO;
randomLabel.backgroundColor = [UIColor clearColor];
[contentView addSubview:randomLabel];
NSDictionary* viewDict = NSDictionaryOfVariableBindings(scrollView, contentView, randomLabel);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|" options:0 metrics:0 views:viewDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|" options:0 metrics:0 views:viewDict]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[contentView]|" options:0 metrics:0 views:viewDict]];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[contentView]|" options:0 metrics:0 views:viewDict]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[randomLabel]-|" options:0 metrics:0 views:viewDict]];
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[randomLabel]-|" options:0 metrics:0 views:viewDict]];
现在您会看到contentView(以及因此contentSize的scrollView)被调整以适应具有标准边距的标签。而且因为我没有指定标签的宽度/高度,它将根据您放入该标签的文本进行调整。
如果您还希望contentView调整到主视图的宽度,您可以重新定义您的viewDictlike,然后添加这些额外的约束(除了上面的所有其他约束):
UIView *mainView = self.view;
NSDictionary* viewDict = NSDictionaryOfVariableBindings(scrollView, contentView, randomLabel, mainView);
[mainView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[contentView(==mainView)]" options:0 metrics:0 views:viewDict]];
滚动视图中的多行标签存在一个已知问题(错误?),如果您希望它根据文本量调整大小,您必须做一些花招,例如:
dispatch_async(dispatch_get_main_queue(), ^{
randomLabel.preferredMaxLayoutWidth = self.view.bounds.size.width;
});