現在比較方便常用的UI適配方案大約以下兩種了:
1.StoryBorad的話用Autolayout+SizeClass,可以適配各種屏幕尺寸和橫豎屏。 剛開始可能比較慢,熟悉了以後還是挺快的。
2.純代碼的話就是用Masonry了,除了動畫上可能有一些複雜,普通的UI適配還是很簡單的。下面就通過代碼瞭解下Masonry的常用方法:
Masonry的簡介可以看這裏:http://www.cocoachina.com/ios/20141219/10702.html
做項目時最經常遇到的情況:在UIViewController裏通過Masonry來實現自動佈局,當最後一個子視圖超過controller.View高度時可以上下滾動。
1)導入Masonry的.h和.m文件,然後初始化一個UIViewController,在view上添加一個ScrollView
UIScrollView *scrollView = [UIScrollView new];
scrollView.showsVerticalScrollIndicator = NO;
[self.view addSubview:scrollView];
[scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
make.bottom.equalTo(self.view);
}];
2)scrollView上添加一個容器View,把子視圖都加到這個容器View上,通過它的高度來使ScrollView實現超出高度自動滾動。
UIView *containerView = [UIView new];
containerView.backgroundColor = [UIColor clearColor];
[scrollView addSubview:containerView];
[containerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(scrollView);
make.width.equalTo(scrollView);
}];
3.向containerView添加各種子視圖,比如添加一個label
UILabel *label1 = [UILabel new];
[self.containerView addSubview:label1];
[label1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.containerView.mas_top).offset(15);
make.height.equalTo(30);
make.left.equalTo(self.containerView).offset(15);
make.right.equalTo(self.containerView).offset(-15);
}];
再添加一個很高的label
UILabel *label2 = [UILabel new];
[self.containerView addSubview:label2];
[label2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(label1.mas_bottom).offset(10);
make.height.equalTo(1000);//超過當前view controller的高度
make.left.equalTo(label1);
make.right.equalTo(label1);
}];
4.設置containerView的mas_bottom
[containerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(label2.mas_bottom);
}];
通過最後一步就可以使scrollView上下滾動了,比較簡單的實現了佈局。