从 html 内容创建一个属性字符串而不删除换行符

bav*_*een 2 ios swift

我尝试从 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))
Run Code Online (Sandbox Code Playgroud)

我想将此属性字符串分配给标签。但它不会显示带有换行符的文本。请帮我解决这个问题

Raj*_*r R 6

全部替换\n<br>. <br>是新行的 html 标签。HTML 参考

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

在此处输入图片说明