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

时间:2016-06-21 19:08:48

标签: ios nsattributedstring

使用int k = ((j + 0) * (j + 0) * (j + 0)); 从HTML创建NSAttributedString时,我发现即使在最后一段之后,也会为每个段落添加NSHTMLTextDocumentType。这会在\n中显示的文本的最后一段下面添加不需要的填充。如何仅删除最后一段的额外填充?

UILabel

enter image description here enter image description here

2 个答案:

答案 0 :(得分:4)

Swift 4版本:

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

sample@exam - valid,
sample@exam.com - valid,
sample@exam.com.in - valid,
sample@.exam - invalid,
sample@exam. - invalid,

换行符多余的原因似乎源于xmllib处理html的方式。它将“无标签”字符串包装到if let lastCharacter = attrStr.string.last, lastCharacter == "\n" { attrStr.deleteCharacters(in: NSRange(location: attrStr.length-1, length: 1)) } 标记中,并且该标记默认添加换行符。

答案 1 :(得分:2)

当我在这些情况下检查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>";

一种解决方法,但它可以解决问题。