前言:在实际的开发过程中经常会遇到计算文本的高度及添加行间距,现在总结几种处理方式
1.用NSString的这种方法,宽度限定,计算高度,或者高度限定计算宽度,简单方便
CGRect titleSize = [data.content boundingRectWithSize:CGSizeMake(300,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
2.用Label的自适应来计算高度
UILabel *contentLabel = [UILabel new];
contentLabel.font = [UIFont boldSystemFontOfSize:15];
contentLabel.textColor = [UIColor colorWithRGB:0x333333 alpha:1.0];
contentLabel.text = @"这是一段计算高度的文本。。。。。。";
contentLabel.numberOfLines = 0;
contentLabel.lineBreakMode = NSLineBreakByWordWrapping;
//计算label的高度
CGSize baseSize = CGSizeMake(SCREEN_WIDTH -30, CGFLOAT_MAX);
CGSize labelSize = [contentLabel sizeThatFits:baseSize];
CGFloat height = labelSize.height;
NSLog(@"height = %f",height);
3.使用UITextView的内容自适应
代码与label的自适应类似,就不贴代码了。
4.设置行间距
NSString *content = @"这是一段设置行间距为5的文本。。。。。。。";
NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString: content];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:5];//设置距离
[attriString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [content length])];
contentLabel.attributedText = attriString;
设置了行间距的文本,用第二种方式能够计算出设置了行间距的文本的高度,很适用。