使用属性文本获取标签的动态高度(属性文本包含HTML字符串)

时间:2015-12-19 04:43:19

标签: ios

我想要属性文本的动态高度...
用我的代码有时候我得到了完美的高度而不是所有的时间...当我的html文本太大时,我的错误高度...(当我的html内容较少但html内容大小不起作用时,它工作正常太大了)

对于html内容属性文本

,我的大小如下所示
  1. 我按照以下方式将我的html字符串转换为属性字符串  NSDictionary * fontDict = [NSDictionary dictionaryWithObject:fontRegular(13)forKey:NSFontAttributeName]; attrCoupon = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@" ,_ObjCoupon.coupon_detail] attributes:fontDict];

  2. 我按以下方式获取属性字符串的高度  CGRect rect = [attrCoupon boundingRectWithSize:(CGSize){self.tbl_details.frame.size.width,CGFLOAT_MAX}                     选项:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading                     上下文:无];

    • (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { CGRect rect = [attrCoupon boundingRectWithSize:(CGSize){self.tbl_details.frame.size.width - 30,CGFLOAT_MAX}                                         选项:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading                                         上下文:无];

      CGSize finalSize = rect.size; return finalSize.height; }

  3. 4.-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

     NSAttributedString *attMerchnat1 = [[NSAttributedString alloc] initWithData:[_ObjCoupon.coupon_detail dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute:              NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    
                CGRect rect = [attMerchnat boundingRectWithSize:(CGSize){self.tbl_details.frame.size.width, CGFLOAT_MAX}options:NSStringDrawingUsesLineFragmentOrigin
                               context:nil];
    
                cell.lblDetail.font = fontRegular(13);
                cell.lblDetail.attributedText = attMerchnat1;
                cell.lblDetail.frame = CGRectMake(10,3,cell.frame.size.width-20, rect.size.height);
                cell.lblDetail.numberOfLines = 0;
                cell.lblDetail.font = fontRegular(13);
                [cell.lblDetail sizeToFit];
    

    我已尝试在堆栈上提供的所有解决方案,但没有任何作用......我需要帮助

1 个答案:

答案 0 :(得分:0)

请使用此方法。

- (CGSize)getSizeforController:(id)view{
    UILabel *tempView =(UILabel *)view;
    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    context.minimumScaleFactor = 0.8;
    float width = tempView.frame.size.width;
    CGSize size=[tempView.text boundingRectWithSize:CGSizeMake(width, 2000)
                                            options:NSStringDrawingUsesLineFragmentOrigin
                                         attributes:@{ NSFontAttributeName : tempView.font}
                                            context:context].size;
    return size;
}

这可能会有所帮助。