首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从使用NSHTMLTextDocumentType创建的NSAttributedString中删除最后一段下面的填充

如何从使用NSHTMLTextDocumentType创建的NSAttributedString中删除最后一段下面的填充
EN

Stack Overflow用户
提问于 2016-06-22 03:08:48
回答 2查看 2.4K关注 0票数 11

当使用NSHTMLTextDocumentType从HTML创建NSAttributedString时,我发现它会为每个段落添加一个\n,甚至在最后一段之后也是如此。这是在UILabel中显示的文本的最后一段下面添加不需要的填充。如何只删除最后一段的额外填充?

代码语言:javascript
复制
NSString *style = @"<style> body { font-family: Avenir; font-size: 18px; color: blue; } p:last-of-type { margin: 0; }</style>";
NSString *html = @"<p>A whole bunch of sample text goes right here.</p><p>Now here's another paragraph that unfortunately has an extra line underneath the text adding undesired padding to the label. :(</p>";
NSString *styledHtml = [NSString stringWithFormat:@"%@%@", style, html];

self.label.attributedText = [[NSMutableAttributedString alloc] initWithData:[styledHtml dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];

EN

回答 2

Stack Overflow用户

发布于 2018-08-02 05:03:49

Swift 4版本:

由于您使用的是NSMutableAttributedString对象,因此可以像这样删除末尾的换行符(如果存在):

代码语言:javascript
复制
if let lastCharacter = attrStr.string.last, lastCharacter == "\n" {
    attrStr.deleteCharacters(in: NSRange(location: attrStr.length-1, length: 1))
}

额外换行符的原因似乎源于xmllib处理html的方式。它将“无标记”字符串包装到一个<p>标记中,默认情况下,该标记会添加一个换行符。

票数 9
EN

Stack Overflow用户

发布于 2017-01-02 18:16:00

不知道它是否仍然相关,当我检查这些情况下的NSAttributedString输出时,我看到<p>标签在每个闭包后面添加了一些默认字体设置的字符:

代码语言:javascript
复制
{
NSColor = "kCGColorSpaceModelRGB 1 1 1 1 ";
NSFont = "<UICTFont: 0x7f94e932a720> font-family: \"Times New Roman\"; font-weight: normal; font-style: normal; font-size: 1.00pt";
NSKern = 0;
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 20/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n), Lists (\n), BaseWritingDirection 0, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0";
NSStrokeColor = "kCGColorSpaceModelRGB 1 1 1 1 ";
NSStrokeWidth = 0;

}

因此,我没有使用<p>标记,而是用<span>标记包装了所有内容:

代码语言:javascript
复制
NSString *html = @"<span style=\"[STYLE CAN BE ADDED HERE]\">A whole bunch of sample text goes right here.</span><br /><span>Now here's another paragraph that unfortunately has an extra line underneath the text adding undesired padding to the label. :(</span>";

这是一种权宜之计,但它确实起到了作用。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37952687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档