一、首先,写一个工具类(NSString的分类,增加两个功能,计算高度宽度)
#import "NSString+Extension.h"
@implementation NSString (Extension)
#pragma mark -根据宽度,字号来计算字符串的高度 - (float) heightWithFont: (UIFont *) font withinWidth: (float) width{ CGRect textRect = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil]; return ceil(textRect.size.height); } #pragma mark -根据字号来计算字符串的宽度 - (float) widthWithFont: (UIFont *) font{ CGRect textRect = [self boundingRectWithSize:CGSizeMake(MAXFLOAT, font.pointSize) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil]; return ceil(textRect.size.width); }
二、为了适配不同系统,字体字号作如下封装:
/* * 自定义字号大小 */ -(UIFont *)jyeFontWithName:(NSString *)name size:(CGFloat)size{ UIFont * font = nil; if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9){ font = [UIFont fontWithName:name size:size]; }else{ if([name rangeOfString:@"Medium"].location == NSNotFound){ font = [UIFont systemFontOfSize:size]; }else{ font = [UIFont boldSystemFontOfSize:size]; } } return font; }
三、在需要计算字符串高度宽度的类中,做如下处理:
NSString *string = @"今日营养配餐提供热量1800千卡,需要饮食之外额外补充钙10mg,铁20mg,锌9.5mg,叶酸200μgDFE,维生素D 10ug,维生素B1 1.2mg,维生素B2 1.2mg。"; UIFont *font = [self jyeFontWithName:@"PingFangSC-Regular" size:13];//需要与UILabel的text保持一致 CGFloat oneRowHeight = [@"test" sizeWithAttributes:@{NSFontAttributeName:font}].height;//test 只是随便取得一个字符串,只要不超过一行就可以 CGFloat textHeight = [string heightWithFont:font withinWidth:self.frame.size.width-30]; CGFloat rows = textHeight/oneRowHeight; CGFloat realHeight = (rows *ceilf(oneRowHeight)) +(rows - 1)* LineSpace;//行间距 为4 //realHeight 就是字符串的高度啦,此时你就可以根据交互设计图编写相应的UILabel的frame啦
四、UILabel 设置行间距
UILabel * hotLabel = [[UILabel alloc]init]; hotLabel.frame = CGRectMake(15, 20, sectionView.frame.size.width - 30, realHeight); hotLabel.textColor = JYEColor(163, 165, 173); hotLabel.numberOfLines = 0; hotLabel.font = [self jyeFontWithName:@"PingFangSC-Regular" size:13]; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string]; NSRange range = [string rangeOfString:@"今日营养配餐"]; [attributedString addAttribute:NSForegroundColorAttributeName value:JYEColor(72, 75, 91) range:range]; [attributedString addAttribute:NSFontAttributeName value:[self jyeFontWithName:@"PingFangSC-Medium" size:13] range:range]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setLineSpacing:4];//调整行间距 [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])]; hotLabel.attributedText = attributedString;