如何获得HTML归属文本的真实高度

Zha*_*ang 6 html objective-c nsattributedstring autolayout ios7

我这里有一个复杂的场景.

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

...
{
    id: 3,
    name: "Content Title",
    description: "<p>This is a paragraph block</p><p>This is another paragraph</p>",
}
Run Code Online (Sandbox Code Playgroud)

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

所以像这样的字符串:

"Hello World" 
Run Code Online (Sandbox Code Playgroud)

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

"<h1>Hello World</h1>"
Run Code Online (Sandbox Code Playgroud)

真实高度可以潜在地是大于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);
}
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?

Ste*_*Bob 0

在获取实际高度时只需要考虑:字体大小、行高、边距、填充、边框和固定高度值。

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

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