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

Jor*_*n H 11 nsattributedstring ios

在创建一个NSAttributedStringHTML时,使用NSHTMLTextDocumentType,我发现\n即使在最后一段之后也会为每个段落添加一个.这是在文本的最后一段下面添加了不需要的填充UILabel.如何仅删除最后一段的额外填充?

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];
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述

小智 6

Swift 4版本:

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

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

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