【问题标题】:How to get real height of HTML attributed text如何获取 HTML 属性文本的真实高度
【发布时间】:2014-05-17 19:32:37
【问题描述】:

这里有一个复杂的场景。

我有一个将 JSON 数据发送回我的应用程序的 Web 服务器,其中一条数据是 HTML 文本,例如 json:

...
{
    id: 3,
    name: "Content Title",
    description: "<p>This is a paragraph block</p><p>This is another paragraph</p>",
}

您可能知道,HTML 属性文本增加了另一层复杂性,因为 HTML 标签会修改实际文本的高度。

这样的字符串:

"Hello World" 

可能只有 10 像素高作为普通字符串,但如果格式如下:

"<h1>Hello World</h1>"

真实高度可能高于 10 像素。

我想知道的是如何计算实际高度

这就是我使用属性字符串计算 UILabel 高度的方式,但它似乎只给了我适合文本像素的高度,而不是实际的 HTML 元素块大小:

-(CGFloat)dynamicHeightForHTMLAttributedString:(NSString *)dataString UsingWidth:(CGFloat)width AndFont:(UIFont *)font
{
    NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font
                                                                forKey:NSFontAttributeName];

    NSMutableAttributedString *htmlString =
    [[NSMutableAttributedString alloc] initWithData:[dataString dataUsingEncoding:NSUTF8StringEncoding]
                                            options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                      NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]}
                                 documentAttributes:NULL error:nil];

    [htmlString addAttributes:attrsDictionary range:NSMakeRange(0, htmlString.length)];

    CGRect rect = [htmlString boundingRectWithSize:(CGSize){width, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil];

    CGSize size = rect.size;

    return ceilf(size.height);
}

这是正确的做法吗?

【问题讨论】:

    标签: html objective-c ios7 autolayout nsattributedstring


    【解决方案1】:

    只有在获取实际高度时您必须考虑的事项:字体大小、行高、边距、内边距、边框和固定高度值。

    您可以检查所有这些并进行计算。

    或者如果您可以使用 javascript,只需检查 element.clientHeight

    【讨论】:

      猜你喜欢
      • 2013-02-16
      • 2014-09-21
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 2019-05-26
      • 1970-01-01
      • 2011-07-04
      相关资源
      最近更新 更多