【发布时间】: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