您的位置:首页 > 产品设计 > UI/UE

UILabel,DTAttributedLabel 关于计算高度

2013-06-23 20:52 579 查看
UILabel 在UITableView中显示时一般要提前计算好高度,网上普遍的解决方案是用constrainedToSize函数

CGSize strSize = [str sizeWithFont:font constrainedToSize:CGSizeMake(_w, 9999) lineBreakMode:UILineBreakModeWordWrap];


但是有个缺陷,如果长度太长,高度就可能算不准了。

对于DTAttributedLabel就更加算不准确了。

我的解决方案是用UIView自带的sizeToFit函数,先将view的高度设得最大,设置文字,然后sizeToFit就会得到最精确的高度,这种效率肯定没有上面的高。不过能很好的解决问题,下面给出DTAttributedLabel高度的函数。

+(float)getStringHeight:(NSString*)str Font:(UIFont*)font Wide:(float)_w{

DTAttributedLabel* dtLabel = [[DTAttributedLabel alloc] initWithFrame:CGRectMake(0,0, _w, 9999)];
dtLabel.lineBreakMode = UILineBreakModeWordWrap;
CGFloat gapHeight = DT_LABEL_GAPH;
CTParagraphStyleSetting gap;
gap.spec = kCTParagraphStyleSpecifierLineHeightMultiple;
gap.value = &gapHeight;
gap.valueSize = sizeof(float);

CGFloat maxHeight = DT_LINE_MAX_HEIGHT;
CTParagraphStyleSetting maxLineHeight;
maxLineHeight.spec = kCTParagraphStyleSpecifierMaximumLineHeight;
maxLineHeight.value = &maxHeight;
maxLineHeight.valueSize = sizeof(float);

CTParagraphStyleSetting settings[] = {
gap,
maxLineHeight
};
CTParagraphStyleRef style = CTParagraphStyleCreate(settings,sizeof(settings)/sizeof(CTParagraphStyleSetting));
NSMutableAttributedString* attributeStr = [[NSMutableAttributedString alloc] initWithString:str];
[attributeStr addAttribute:(NSString*)kCTParagraphStyleAttributeName value:(id)style range:NSMakeRange(0, [attributeStr length])];
CFRelease(style);
CTFontRef tempFont = CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize, NULL);
[attributeStr addAttribute:(NSString*)kCTFontAttributeName value:(id)tempFont range:NSMakeRange(0, [attributeStr length])];
CFRelease(tempFont);

CTFontRef emojiFont = CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize - EMOJI_SIZE_OFFSET, NULL);
NSArray* emojiRanges = [attributeStr.string emojiRanges];
for (int i = 0; i < [emojiRanges count]; i++) {
NSString* rangeStr = [emojiRanges OBJECT_AT(i)];
NSRange emojiRange = NSRangeFromString(rangeStr);
[attributeStr addAttribute:(NSString*)kCTFontAttributeName value:(id)emojiFont range:emojiRange];
}
CFRelease(emojiFont);

[dtLabel setAttributedString:attributeStr];
[dtLabel sizeToFit];

float h = frameH(dtLabel);
[dtLabel release];
[attributeStr release];

return h;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: