您好, , 海量一手媒体资源,专业、正规、高效,为企业提供一站式营销推广服务!
温馨提示
运营小帮手
一站式互联网营销服务平台
  全国免费咨询热线
0755-23071973
运营小帮手
软文发稿
PC端 选择媒体
更方便、更快捷!
查看媒体价格
软文发布、软文代写、百科制作、问答营销、微信营销、微信营销
查看媒体价格
当前位置: 运营小帮手首页 > 新闻中心 > 文章正文

iOS Masonry ScrollView循环布局

说到iOS自动布局,有很多的解决办法。有的人使用xib/storyboard自动布局,也有人使用frame来适配。对于前者,笔者并不喜欢,也不支持。对于后者,更是麻烦,到处计算高度、宽度等,千万大量代码的冗余,对维护和开发的效率都很低。

笔者在这里介绍纯代码自动布局的第三方库:Masonry。这个库使用率相当高,在全世界都有大量的开发者在使用,其star数量也是相当高的。

效果图

本节详解Masonry的循环创建视图的基本用法,先看看效果图:

核心代码

@interfaceScrollViewController()

@property(nonatomic,strong)UIScrollView*scrollView;

@end

@implementationScrollViewController

-(void)viewDidLoad{
[superviewDidLoad];

self.scrollView=[[UIScrollViewalloc]init];
self.scrollView.pagingEnabled=NO;
[self.viewaddSubview:self.scrollView];
self.scrollView.backgroundColor=[UIColorlightGrayColor];

CGFloatscreenWidth=[UIScreenmainScreen].bounds.size.width;
UILabel*lastLabel=nil;
for(NSUIntegeri=0;i<20;++i){
UILabel*label=[[UILabelalloc]init];
label.numberOfLines=0;
label.layer.borderColor=[UIColorgreenColor].CGColor;
label.layer.borderWidth=2.0;
label.text=[selfrandomText];

//WemustpreferredMaxLayoutWidthpropertyforadaptingtoiOS6.0
label.preferredMaxLayoutWidth=screenWidth-30;
label.textAlignment=NSTextAlignmentLeft;
label.textColor=[selfrandomColor];
[self.scrollViewaddSubview:label];

[labelmas_makeConstraints:^(MASConstraintMaker*make){
make.left.mas_equalTo(15);
make.right.mas_equalTo(self.view).offset(-15);

if(lastLabel){
make.top.mas_equalTo(lastLabel.mas_bottom).offset(20);
}else{
make.top.mas_equalTo(self.scrollView).offset(20);
}
}];

lastLabel=label;
}

[self.scrollViewmas_makeConstraints:^(MASConstraintMaker*make){
make.edges.mas_equalTo(self.view);

//让scrollview的contentSize随着内容的增多而变化
make.bottom.mas_equalTo(lastLabel.mas_bottom).offset(20);
}];
}

-(UIColor*)randomColor{
CGFloathue=(arc4random()%256/256.0);//0.0to1.0
CGFloatsaturation=(arc4random()%128/256.0)+0.5;//0.5to1.0,awayfromwhite
CGFloatbrightness=(arc4random()%128/256.0)+0.5;//0.5to1.0,awayfromblack
return[UIColorcolorWithHue:huesaturation:saturationbrightness:brightnessalpha:1];
}

-(NSString*)randomText{
CGFloatlength=arc4random()%50+5;

NSMutableString*str=[[NSMutableStringalloc]init];
for(NSUIntegeri=0;i<length;++i){
[strappendString:@"测试数据很长,"];
}

returnstr;
}

@end

讲解

对于循环创建,我们需要记录下一个视图所依赖的控件,这里使用了lastLabel来记录。

我们要想让scrollviewcontentSize随内容的变化而变化,那么就我们一定要添加注意添加约束:

[self.scrollViewmas_makeConstraints:^(MASConstraintMaker*make){
make.edges.mas_equalTo(self.view);

//让scrollview的contentSize随着内容的增多而变化
make.bottom.mas_equalTo(lastLabel.mas_bottom).offset(20);
}];

对于scrollviewtableview,我们不能使用bottom来计算其高,因为这个属性对于scrollviewtableview来说,不用用来计算高度的,而是用于计算contentSize.height的。我们要想随内容而变化,以便可滚动查看,就必须设置bottom约束。

源代码

大家可以到笔者的github下载源代码:MasonryDemo

温馨提示:本节所讲内容对应于ScrollViewController中的内容

推荐阅读

CocoaChina上有一篇文章讲得也不错,叫Masonry介绍与使用实践:快速上手AutolayoutIOS自适应前段库-Masonry的使用

文章中所讲的内容属于很基础的内容,如果有任何疑问可以联系博主哦!

关键词:

猜您可能需要的服务: