当使用NSHTMLTextDocumentType
从HTML创建NSAttributedString
时,我发现它会为每个段落添加一个\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];
发布于 2018-08-02 05:03:49
Swift 4版本:
由于您使用的是NSMutableAttributedString对象,因此可以像这样删除末尾的换行符(如果存在):
if let lastCharacter = attrStr.string.last, lastCharacter == "\n" {
attrStr.deleteCharacters(in: NSRange(location: attrStr.length-1, length: 1))
}
额外换行符的原因似乎源于xmllib处理html的方式。它将“无标记”字符串包装到一个<p>
标记中,默认情况下,该标记会添加一个换行符。
发布于 2017-01-02 18:16:00
不知道它是否仍然相关,当我检查这些情况下的NSAttributedString输出时,我看到<p>
标签在每个闭包后面添加了一些默认字体设置的字符:
{
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>
标记包装了所有内容:
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>";
这是一种权宜之计,但它确实起到了作用。
https://stackoverflow.com/questions/37952687
复制相似问题