版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1337811
在项目中我们有时会遇到这样的需求:显示一段文字,但这段文字最多显示4行。
我们首先考虑没有行数显示的情况:
UILabel * lbl = [UILabel alloc init];
lbl.backgroundColor = UIColor redColor;
lbl.textColor = UIColor blackColor;
lbl.numberOfLines = 0;
lbl.text = @"连卡精神分裂就离开家啊";
lbl.lineBreakMode = UILineBreakModeWordWrap;
NSMutableDictionary * dic = NSMutableDictionary dictionary;
dicNSFontAttributeName = UIFont systemFontOfSize:17;
CGRect rect = lbl.text boundingRectWithSize:CGSizeMake(100, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil;
NSLog(@"%f-----%f", rect.size.width, rect.size.height);
lbl.frame = (CGRect){{0, 20}, rect.size};
self.view addSubview:lbl;
这样单元格高度会进行自适应。
如果显示固定行数,我们需要知道固定行数时单元格的高度
UILabel * lbl = [UILabel alloc init];
lbl.backgroundColor = UIColor redColor;
lbl.textColor = UIColor blackColor;
lbl.numberOfLines = 0;
lbl.text = @"连卡精神分裂就离开家啊";
lbl.lineBreakMode = UILineBreakModeWordWrap;
NSMutableDictionary * dic = NSMutableDictionary dictionary;
dicNSFontAttributeName = UIFont systemFontOfSize:17;
CGRect rect = lbl.text boundingRectWithSize:CGSizeMake(100, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil;
NSLog(@"%f-----%f", rect.size.width, rect.size.height);
lbl.frame = (CGRect){{0, 20}, rect.size};
if (rect.size.height > 102) {
lbl.numberOfLines = 5;
lbl.frame = (CGRect){{0, 20}, {100, 101.435547}};
}
self.view addSubview:lbl;