UILabel设置行间距需要使用属性字符串的方法
其中主要的一段代码是:
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
paraStyle.alignment = NSTextAlignmentLeft;
paraStyle.lineSpacing = UILABEL_LINE_SPACE; //设置行间距
paraStyle.hyphenationFactor = 1.0;
paraStyle.firstLineHeadIndent = 0.0;
paraStyle.paragraphSpacingBefore = 0.0;
paraStyle.headIndent = 0;
paraStyle.tailIndent = 0;
//设置字间距 NSKernAttributeName:@1.5f
NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f};
NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:str attributes:dic];
label.attributedText = attributeStr;
当你需要计算Label的高度的时候,同样把行间距属性加进去就可以了
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
paraStyle.alignment = NSTextAlignmentLeft;
paraStyle.lineSpacing = UILABEL_LINE_SPACE;
paraStyle.hyphenationFactor = 1.0;
paraStyle.firstLineHeadIndent = 0.0;
paraStyle.paragraphSpacingBefore = 0.0;
paraStyle.headIndent = 0;
paraStyle.tailIndent = 0;
NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f};
CGSize size = [str boundingRectWithSize:CGSizeMake(width, HEIGHT) options:NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
return size.height;