gpt4 book ai didi

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

转载 作者:技术小花猫 更新时间:2023-10-29 11:22:21 24 4
gpt4 key购买 nike

当使用 NSHTMLTextDocumentType 从 HTML 创建 NSAttributedString 时,我发现即使在最后一段。这是在 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];

enter image description here enter image description here

最佳答案

swift 4 版本:

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

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

额外换行符的原因似乎源于 xmllib 处理 html 的方式。它将“无标签”字符串包装成 <p>标签,标签默认添加一个换行符。

关于ios - 如何使用 NSHTMLTextDocumentType 从 HTML 创建的 NSAttributedString 中删除最后一段下的填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37952687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com