在設(shè)置了label中文字的字間距饼丘、行間距夸浅、段間距后仑最,獲取label總的高度,嘗試了各種計(jì)算方法帆喇,最后只發(fā)現(xiàn)一種方式是有效的警医。
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber *fontSize = [defaults objectForKey:@"DetailContentFont"];
if (!fontSize) fontSize = @16;
NSMutableParagraphStyle *npgStyle = [[NSMutableParagraphStyle alloc] init];
npgStyle.alignment = NSTextAlignmentJustified;
npgStyle.paragraphSpacing = 16; // 段與段的距離
npgStyle.lineSpacing = 16;
NSDictionary *attr = @{NSFontAttributeName:[UIFont systemFontOfSize:[fontSize integerValue]],NSForegroundColorAttributeName:[UIColor darkGrayColor],NSParagraphStyleAttributeName:npgStyle};
CGSize size = CGSizeMake(CYBMacros.kScreenWidth-36*CYBMacros.kWidthScale, CGFLOAT_MAX);
NSString *displayStr = [self.detailInfoModel.content stringByAppendingString:@"\n"];
CGFloat height = [displayStr boundingRectWithSize:size
options:\
NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:attr context:nil].size.height;
DebugLog(@"計(jì)算的文字高度=%.2f", height)
return height;
每次使用原字符串內(nèi)容計(jì)算完高度時(shí),最后一行都無(wú)法顯示坯钦,
解決方案
在文章末尾添加一個(gè)換行符预皇,然后再計(jì)算總高度。
其中婉刀,options的枚舉值說(shuō)明:
typedef NS_OPTIONS(NSInteger, NSStringDrawingOptions) {
NSStringDrawingUsesLineFragmentOrigin = 1 << 0,
// 整個(gè)文本將以每行組成的矩形為單位計(jì)算整個(gè)文本的尺寸
// The specified origin is the line fragment origin, not the base line origin
NSStringDrawingUsesFontLeading = 1 << 1,
// 使用字體的行間距來(lái)計(jì)算文本占用的范圍吟温,即每一行的底部到下一行的底部的距離計(jì)算
// Uses the font leading for calculating line heights
NSStringDrawingUsesDeviceMetrics = 1 << 3,
// 將文字以圖像符號(hào)計(jì)算文本占用范圍,而不是以字符計(jì)算突颊。也即是以每一個(gè)字體所占用的空間來(lái)計(jì)算文本范圍
// Uses image glyph bounds instead of typographic bounds
NSStringDrawingTruncatesLastVisibleLine
// 當(dāng)文本不能適合的放進(jìn)指定的邊界之內(nèi)鲁豪,則自動(dòng)在最后一行添加省略符號(hào)。如果NSStringDrawingUsesLineFragmentOrigin沒(méi)有設(shè)置律秃,則該選項(xiàng)不生效
// Truncates and adds the ellipsis character to the last visible line if the text doesn't fit into the bounds specified. Ignored if NSStringDrawingUsesLineFragmentOrigin is not also set.
}