本文转自http://www.voidcn.com/blog/potato512/article/p-5789787.html
UILabel在使用过程中,一个重要的特性是可以进行多行显示,或者是自定义显示行数。同时呢,在设置多行显示的过程中,还可以计算出label所需要的高度。
但不管是使用frame,还是使用masonry进行设置,都需要设置显示行数属性,即 属性"numberOfLines"。当在使用frame设置时,可以很好的计算其高度,而在使用masonry时,因为不需要设置frame,及其高度。那masonry时具体应该怎么进行设置呢?多行显示是又怎么设置呢?
使用masonry设置label显示的效果如下图所示:
具体见代码
// 显示一行,固定高度40
UILabel *label = [[UILabelalloc] initWithFrame:CGRectZero];
[self.viewaddSubview:label];
label.backgroundColor = [UIColorcolorWithWhite:0.5alpha:0.3];
label.text =@"Masonry是一个轻量级的布局框架与更好的包装AutoLayout语法。";
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(10.0);
make.right.mas_equalTo(-10.0);
make.top.mas_equalTo(10.0);
make.height.mas_equalTo(40.0);
}];
// 显示二行,固定高度40
UILabel *label2 = [[UILabelalloc] initWithFrame:CGRectZero];
[self.viewaddSubview:label2];
label2.backgroundColor = [UIColorcolorWithWhite:0.5alpha:0.3];
label2.text =@"Masonry是一个轻量级的布局框架与更好的包装AutoLayout语法。";
label2.font = [UIFontsystemFontOfSize:15.0];
label2.numberOfLines =2;
[label2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(10.0);
make.right.mas_equalTo(-10.0);
make.top.mas_equalTo(10.0);
make.height.mas_equalTo(40.0);
}];
//显示多行,自适应高度
UILabel *label3 = [[UILabelalloc] initWithFrame:CGRectZero];
[self.viewaddSubview:label3];
label3.backgroundColor = [UIColorcolorWithWhite:0.5alpha:0.3];
label3.text =@"Masonry是一个轻量级的布局框架与更好的包装AutoLayout语法。Masonry有它自己的布局方式,描述NSLayoutConstraints使布局代码更简洁易读。Masonry支持iOS和Mac OS X。Masonry github地址:https://github.com/SnapKit/Masonry";
label3.preferredMaxLayoutWidth = (WidthScreen -10.0 * 2);
[label3 setContentHuggingPriority:UILayoutPriorityRequiredforAxis:UILayoutConstraintAxisVertical];
label3.numberOfLines =0;
[label3 mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(10.0);
make.right.mas_equalTo(-10.0);
make.top.mas_equalTo(10.0);
}];
注意:使用masonry进行label的多行显示设置时,主要是如下两个参数的设置
1、@property(nonatomic)CGFloat preferredMaxLayoutWidth
2、- (void)setContentHuggingPriority:(UILayoutPriority)priority forAxis:(UILayoutConstraintAxis)axis