html - 如何获得 HTML 属性文本的真实高度

标签 html objective-c ios7 autolayout nsattributedstring

这里的场景有点复杂。

我有一个网络服务器将 JSON 数据发送回我的应用程序,其中一条数据是 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 元素 block 大小:

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

这是正确的做法吗?

最佳答案

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

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

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

关于html - 如何获得 HTML 属性文本的真实高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22880539/

相关文章:

ios - 拉动刷新时旋转图像

ios - 从 nsdata 获取字节附加额外的垃圾字符

ios - 如何安全地停止使用多点连接发送图像

ios - 按钮高亮状态的延迟

javascript - 我是否需要 Goodreads API key 来检索图书元数据?

html - 为什么 float 会把 div 上面的东西弄乱?

objective-c - 在 Cocoa 中的对象/线程之间传递数据

jQuery 手机 : fixed footer glitches

javascript - 是否有可能开发一个接受 Selenium 自动化的浏览器工具栏

ios - 如何使用返回/输入键创建 UIKeyCommand?