UILabel设置行间距并且计算文本高度所占内容
有时候我们在有些文本设计中需要对行间距有一些特殊的要求,那么uilabel是不能直接设置行间距的,那么我们应该如何来设置行间距呢?
设置行间距
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.stringData];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:10];//调整行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.stringData length])];
contentLabel.attributedText = attributedString;
计算带有行间距的文本的高度
- (CGSize)getSizeWithLabelString:(NSString *)text
font:(UIFont *)font
width:(NSInteger)width
lineSpace:(NSInteger)lineSpace {
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:text];
NSMutableParagraphStyle *paragraphStyle =
[[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpace];
[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, text.length)];
CGSize stringSize =
[text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading |
NSStringDrawingTruncatesLastVisibleLine
attributes:@{
NSFontAttributeName : font,
NSParagraphStyleAttributeName : paragraphStyle
} context:nil].size;
return stringSize;
}