我尝试从 html 响应创建属性字符串以在标签上显示它。但是,当我创建字符串时,我遇到了一些问题。转换从字符串中删除换行符。
let text = "test test test\n\nline 2 test test test\n\nline 3 test test test test test test test test test test test test test test test test test testtest test test test test testtest test test test test testtest test test test test testtest test test test test test"
let attributedString = NSMutableAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
attributedString.addAttribute(.font, value: UIFont.body, range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(.foregroundColor, value: UIColor.charcoal, range: NSMakeRange(0, attributedString.length))
我想将这个属性字符串分配给一个标签。但它不显示带有换行符的文本。请帮我解决这个问题
最佳答案
全部替换\n
与 <br>
. <br>
是换行的 html 标签。 HTML Reference
var text = "<ol><li>Coffee</li><li>Tea</li><li>Milk</li></ol><ul><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
\ntest test test\n\nline 2 test test test\n\nline 3 test test test test test test test test test test test test test test test test test testtest test test test test testtest test test test test testtest test test test test testtest test test test test test"
text = text.replacingOccurrences(of: "\n", with: "<br>")
lbl.numberOfLines = 0
guard let data = text.data(using: String.Encoding.utf8) else {
return
}
do {
let attributedString = try NSMutableAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
attributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 15), range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(.foregroundColor, value: UIColor.red, range: NSMakeRange(0, attributedString.length))
lbl.attributedText = attributedString
} catch let error {
print(error.localizedDescription)
}
关于ios - 从 html 内容创建一个 attributedString 而不删除换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56232222/