UILabel,DTAttributedLabel 关于计算高度

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值