And*_*w H 8 html objective-c nsattributedstring uilabel ios
我有文本,其中包含我试图在视图上呈现的HTML格式.目前我正在使用一个NSAtributedString来显示一个文本UILabel.
我获得了如下的属性字符串:
NSString *htmlString = @"<html>"
" <head>"
" <style type='text/css'>"
" body { font: 12pt 'Helvetica'; color: #111111; }"
" </style>"
" </head>"
" <body>";
htmlString = [htmlString stringByAppendingString:self.descriptionText];
htmlString = [htmlString stringByAppendingString:@"</body></html>"];
NSError *err = nil;
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithData: [htmlString dataUsingEncoding:NSUTF8StringEncoding]
options: @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
documentAttributes: nil
error: &err];
Run Code Online (Sandbox Code Playgroud)
然后将其分配给我的标签attributedText属性.self.descriptionText属性NSString可以包含简单的HTML标记,例如带有内联样式的p标记或span标记.在另一个StackOverflow帖子中找到了将字符串包装在HTML文档中的技术.
将UILabel被设定为行= 0和换行符=自动换行.我看到的行为是标签正确生长以容纳整个字符串,但无论字符串有多长,字符串的最后一行都不会呈现.
这是一个带有两个标签的屏幕截图.顶部标签(带黄色背景)中包含我的HTML属性字符串.您可以看到标签的大小适合允许3行文本,但只有两行被渲染,其余的被截断.第二个标签(带有红色背景)已经为其Text属性分配了一个纯字符串,它绘制得很好.
示例图像中使用的HTML字符串包含以下文本:
<p>With the world's longest fan-vaulted ceiling, an original Reubens painting, and an excellent collection of medieval stained glass, this chapel has intrigue from multiple angles</p>
Run Code Online (Sandbox Code Playgroud)

一个可接受的答案将解释我如何防止最后一行被截断或提供一种简单的替代方法来将HTML文本呈现给视图.谢谢.
And*_*w H 10
好的,我明白了.这不是一个明显的解决方案,但我发现它之后确实做了一个面孔.
问题是p标签被赋予边距和/或填充,这将文本推到了界限之外UILabel.我不知道为什么在计算字符串的大小时不考虑它,但我不在乎了.
解决方案是我添加p {margin:0; padding:0;}到我在HTML字符串前面的样式标记.现在,所有字符串都在UILabel中正确绘制.
刚刚碰到这个.显然,当显示attributedText具有NSParagraphStyleAttributeName属性集的UILabel时,计算正确的大小会有一些困难.
我通过从my中删除此属性解决了我的问题,NSMutableAttributedString然后将其分配给我的标签,如下所示:
[mutableAttributedString removeAttribute:NSParagraphStyleAttributeName range:NSMakeRange(0, mutableAttributedString.length)];
Run Code Online (Sandbox Code Playgroud)
效果是一样的,但它比预先添加一些内联css感觉有点整洁.
| 归档时间: |
|
| 查看次数: |
2658 次 |
| 最近记录: |