如何从使用 NSHTMLTextDocumentType 从 HTML 创建的 NSAttributedString 中删除最后一段下的填充 [英] How to remove padding under last paragraph from NSAttributedString created from HTML using NSHTMLTextDocumentType

查看:326
本文介绍了如何从使用 NSHTMLTextDocumentType 从 HTML 创建的 NSAttributedString 中删除最后一段下的填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When creating an NSAttributedString from HTML, using NSHTMLTextDocumentType, I'm finding it will add an \n for each paragraph even after the last paragraph. This is adding undesired padding underneath the last paragraph of text that's shown in a UILabel. How does one remove that extra padding for the last paragraph only?

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];

推荐答案

Swift 4 版本:

Swift 4 version:

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

Since you are using an NSMutableAttributedString object you can remove the newline character at the end (if it exists) like this:

if let lastCharacter = attrStr.string.last, lastCharacter == "\n" {
    attrStr.deleteCharacters(in: NSRange(location: attrStr.length-1, length: 1))
}

额外换行符的原因似乎源于 xmllib 处理 html 的方式.它将无标签"字符串包装到一个 <p> 标签中,并且该标签默认添加一个换行符.

The reason for the extra newline character seems to originate from the way xmllib processes the html. It wraps the "tagless" string into a <p> tag and the tag adds a newline character by default.

这篇关于如何从使用 NSHTMLTextDocumentType 从 HTML 创建的 NSAttributedString 中删除最后一段下的填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆