【iOS】 Label设置行距自适应高度

    xiaoxiao2021-12-14  21

    关于label自适应高度想必只要有一点开发基础的朋友都应该了解,这边我就不多提了,贴上一段自己写的计算的代码。 + (CGFloat)textHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)size{ if ([Helper getCurrentIOS] >= 7.0) { //iOS7之后 /* 第一个参数: 预设空间 宽度固定 高度预设 一个最大值 第二个参数: 行间距 如果超出范围是否截断 第三个参数: 属性字典 可以设置字体大小 */ NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:size]}; CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil]; return rect.size.height; }else { //iOS7之前 /* 1.第一个参数 设置的字体固定大小 2.预设 宽度和高度 宽度是固定的 高度一般写成最大值 3.换行模式 字符换行 */ CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:size] constrainedToSize:CGSizeMake(textWidth, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping]; return textSize.height;//返回 计算出得行高 } }

    项目中很多的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给出的效果。

    转载请注明原文地址: https://ju.6miu.com/read-962253.html

    最新回复(0)