概述
项目适配到第2个页面就遇到了问题,tableViewCell中添加了一个scrollView,scrollView中有个缩放imageView,于是各种问题。
scrollView的问题解决了,下篇将会介绍tableViewCell使用autoLayout的问题。
scrollView有一个contentSize属性,在以前用时会直接赋值,定义其滚动范围。但在autoLayout下,scrollView的contentSize是由subviews的约束来确定的。因此,我们在scrollView里面设置subviews的约束,不仅需要起到布局内容的作用,同时也起到了设置scrollView的contentSize作用。
具体怎么解决也简单,设置subview的上下左右边距以及宽高,这样就可以确定scrollView的contentSize的滚动范围以及subview的位置。
代码
创建第一个view并设置约束(这个view只是为了和scrollView对比下,和本文内容无关)
UIView *view1 = [[UIView alloc] init];
view1.backgroundColor = [UIColor brownColor];
//要实现自动布局,必须把该属性设置为NO
view1.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:view1];
//通过宏映射成字典[NSDictionary dictionaryWithObjectsAndKeys:v1, @"v1", nil];
NSDictionary *viewsDictionary1 = NSDictionaryOfVariableBindings(view1);
//约束1 横向 Horizontal
[self.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[view1]-10-|"
options:0
metrics:nil
views:viewsDictionary1]];
//约束2 纵向 Vertical
[self.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[view1(50)]"
options:0
metrics:nil
views:viewsDictionary1]];
创建scrollView并设置约束
UIScrollView *scrollView = [[UIScrollView alloc] init];
scrollView.backgroundColor = [UIColor redColor];
//要实现自动布局,必须把该属性设置为NO
scrollView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:scrollView];
//通过宏映射成字典[NSDictionary dictionaryWithObjectsAndKeys:v1, @"v1", nil];
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(scrollView);
//约束1 横向 Horizontal
[self.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[scrollView]-10-|"
options:0
metrics:nil
views:viewsDictionary]];
//约束2 纵向 Vertical
[self.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-100-[scrollView]-30-|"
options:0
metrics:nil
views:viewsDictionary]];
创建scrollView的subView并设置约束:
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor brownColor];
view.translatesAutoresizingMaskIntoConstraints = NO; //要实现自动布局,必须把该属性设置为NO
[scrollView addSubview:view];
//通过宏映射成字典[NSDictionary dictionaryWithObjectsAndKeys:v1, @"v1", nil];
NSDictionary *viewsDictionary2 = NSDictionaryOfVariableBindings(view);
//约束1 横向 Horizontal
[scrollView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[view(400)]-10-|"
options:0
metrics:nil
views:viewsDictionary2]];
[scrollView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-40-[view(200)]-100-|"
options:0
metrics:nil
views:viewsDictionary2]];
3个view中,前2个正常设置约束条件,第3个会发现VFL语句@"H:|-10-[view(400)]-10-|"在普通view布局中肯定会报错的。
效果图

学习AutoLayout(UIScrollView)
参考文章
iOS: How To Make AutoLayout Work On A ScrollView
ScrollView 与 Autolayout