如何从使用 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.