在自动布局中,您无需contentSize手动设置。自动布局与滚动视图的工作方式略有不同,contentSize滚动视图的 由滚动视图的子视图的约束决定。
如果您试图将其强制contentSize为较大的尺寸(例如,您正在实现一些无限滚动条),您可以添加适当大小的子视图,例如:
UIView *containerView = [[UIView alloc] init];
containerView.translatesAutoresizingMaskIntoConstraints = NO;
[self.scrollView addSubview:containerView];
NSDictionary *views = NSDictionaryOfVariableBindings(containerView);
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[containerView]|" options:0 metrics:nil views:views]];
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[containerView(1000)]|" options:0 metrics:nil views:views]];
但是,如果您尝试设置contentSize预期添加子视图,您通常不需要做任何事情,例如上面的代码片段。只需添加您的子视图,提供它们的约束,自动布局将contentSize自动调整滚动视图。
如上所述,使用自动布局,您只需将子视图添加到滚动视图(及其约束),contentSize就会自动为您计算。
不过,这里有一个技巧。有时您想根据屏幕尺寸调整子视图的大小。但是使用这些符号的常用技术是|行不通的。例如,对于滚动视图imageview1内部,通常@"H:|[imageview1]|"不会将 设置imageview1为屏幕的宽度,而是将滚动视图定义contentSize为与 的宽度匹配imageview1,但它没有说明该图像视图的宽度是多少应该!
因此,捕获对滚动视图的superview. 这样,你可以使用类似的东西@"H:|[imageview1(==superview)]|",它不仅说“使滚动视图contentSize等于宽度imageview1”,而且“定义宽度imageview1等于滚动视图的宽度superview”。
因此,例如,要在分页滚动视图中添加三个图像,您可能会执行以下操作:
UIImageView *imageview1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"_DSC0004.jpg"]];
imageview1.contentMode = UIViewContentModeScaleAspectFit;
imageview1.translatesAutoresizingMaskIntoConstraints = NO;
[self.scrollView addSubview:imageview1];
UIImageView *imageview2 = ... // configured similar to imageview1
UIImageView *imageview3 = ... // configured similar to imageview1
UIView *superview = self.scrollView.superview;
NSDictionary *views = NSDictionaryOfVariableBindings(imageview1, imageview2, imageview3, superview);
// not only define the image view's relation with their immediate scroll view,
// but also explicitly set the size in relation to the superview, too!
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[imageview1(==superview)][imageview2(==superview)][imageview3(==superview)]|" options:0 metrics:nil views:views]];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[imageview1(==superview)]|" options:0 metrics:nil views:views]];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[imageview2(==superview)]|" options:0 metrics:nil views:views]];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[imageview3(==superview)]|" options:0 metrics:nil views:views]];
self.scrollView.pagingEnabled = YES;