iOS UIScrollView使用Autolayout
最近项目在迭代更新的时候,需要在之前用Autolayout写的界面里添加一个button,添加完这个button后,iPhone5,iPhone4显示不全了.遇到整个问题后很自然就想到了用UIScrollView,很快就创建了一个占满全屏的UIScrollView,把之前所有的控件有[self.view addSubview:xxx]全部改成[self.scrollView addSubview:xxx],信心满满的点击了一个运行按钮,艹,居然滑动不了......
重新调整了一下思路,解决了此问题,先创建一个UIScrollView没错,然后创建一个contrainerView用于存储之前添加在[self.view]上的控件,把contrainer再添加到scrollview上,最后调整contrainerView的位置即可.
代码:
// 创建一个scrollview UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectZero]; [self.view addSubview:scrollView]; [scrollView mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(self.view); }]; // 创建一个view,这个view里面放置各种view控件,并添加到scrollview上 UIView *contrainerView = [[UIView alloc] initWithFrame:CGRectZero]; [scrollView addSubview:contrainerView]; UIView *view1 = [[UIView alloc] initWithFrame:CGRectZero]; view1.backgroundColor = [UIColor redColor]; [contrainerView addSubview:view1]; [view1 mas_makeConstraints:^(MASConstraintMaker *make) { make.left.top.equalTo(@20); make.right.equalTo(@(-20)); // 宽度不写view显示不出来 make.width.equalTo(@(self.view.frame.size.width - 40)); make.height.equalTo(@200); }]; UIView *view2 = [[UIView alloc] initWithFrame:CGRectZero]; view2.backgroundColor = [UIColor greenColor]; [contrainerView addSubview:view2]; [view2 mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(@100); make.top.equalTo(view1.mas_bottom).offset(10); make.right.equalTo(@(-100)); // 宽度不写view显示不出来 make.width.equalTo(@(self.view.frame.size.width - 200)); make.height.equalTo(@400); }]; UIView *view3 = [[UIView alloc] initWithFrame:CGRectZero]; view3.backgroundColor = [UIColor redColor]; [contrainerView addSubview:view3]; [view3 mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(@20); make.top.equalTo(view2.mas_bottom).offset(10); make.right.equalTo(@(-20)); // 宽度不写view显示不出来 make.width.equalTo(@(self.view.frame.size.width - 40)); make.height.equalTo(@200); }]; // 容器的顶部位置基于最后一个view控制来确定 [contrainerView mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(scrollView); make.bottom.equalTo(view3.mas_bottom).offset(20); }];
如果你不是在wb145230博客园看到本文,请点击查看原文.