iOS UIScrollView使用Autolayout,iosuiscrollview
最近項目在迭代更新的時候,需要在之前用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部落格園看到本文,請點擊查看原文.