项目中很多的label需要根据实际内容计算高度,这个方法能够满足计算动态高度。
如何设置label的行间距 如果设置行间距,那么UI可能会比较难看,一般UI需求都会对行间距有一些要求。 那么如何设置行间距呢? 如果需要设置行间距,我们的label必须给予attributedText(富文本)而不是普通的text,如果设置text那么行间距固定为0,效果就和上图一样十分不美观。 我们可以设置一个富文本进行赋值,对行间距赋值就可以达到效果 /* str 显示的字符串 font 字体大小 lineHeight 行间距 */ - (NSAttributedString *)getAttibuteStringWithString:(NSString *)str textFont:(UIFont *)font lineHeight:(NSInteger)lineHeight{ NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:str]; NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc]init]; paragrapStyle.lineSpacing = lineHeight; NSRange range = NSMakeRange(0, str.length); NSDictionary *attribute = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragrapStyle}; [attributeStr addAttributes:attribute range:range]; return attributeStr; }然后在对label进行赋值,就可以设置行间距了 我们在对他进行刚刚的自适应高度设置
label.attributedText = [self getAttibuteStringWithString:str textFont:[UIFont systemFontOfSize:14] lineHeight:15]; CGFloat labelHeight = [self textHeightFromTextString:str width:300 fontSize:14]; [label setFrame:CGRectMake(20, 50, 300, labelHeight)];效果出来后发现,行间距确实设置了,但是高度不自适应了,这是什么原因呢,原来设置高度的时候我调用的还是原来的设置高度的方法,但是我们现在设置的是设置文本,里面有行间距,如果用原来的方法那么他计算的高度还是按照行间距为0计算,因此我们需要重新写一个方法计算富文本的动态高度。
/* text 显示的字符串 font 字体大小 lineHeight 行间距 */ - (CGFloat)getLabelHeightWithText:(NSString *)text width:(CGFloat)width textFont:(UIFont *)font lineHeight:(NSInteger)lineHeight{ NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init]; paragrapStyle.lineSpacing = lineHeight; NSDictionary *attribute = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragrapStyle}; CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil]; return rect.size.height; }这里几个注意点 1、传入的宽度必须和label显示的最大宽度一致 2、传入的字体必须和设置富文本时候的字体相同 3、传入的行间距必须和富文本的相同 如此一个label既可以设置行距又可以自适应高度,到达UI给出的效果。