UILabel設(shè)置行間距需要使用屬性字符串的方法
其中主要的一段代碼是:
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
paraStyle.alignment = NSTextAlignmentLeft;
paraStyle.lineSpacing = UILABEL_LINE_SPACE; //設(shè)置行間距
paraStyle.hyphenationFactor = 1.0;
paraStyle.firstLineHeadIndent = 0.0;
paraStyle.paragraphSpacingBefore = 0.0;
paraStyle.headIndent = 0;
paraStyle.tailIndent = 0;
//設(shè)置字間距 NSKernAttributeName:@1.5f
NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f};
NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:str attributes:dic];
label.attributedText = attributeStr;
當(dāng)你需要計(jì)算Label的高度的時(shí)候胳施,同樣把行間距屬性加進(jìn)去就可以了
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;