这里的场景有点复杂。
我有一个网络服务器将 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/