ios - 从 html 内容创建一个 attributedString 而不删除换行符

标签 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))

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

最佳答案

全部替换\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)
}

enter image description here

关于ios - 从 html 内容创建一个 attributedString 而不删除换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56232222/

相关文章:

ios block w/self = 无限循环

ios - ASIHTTPRequest 响应数据 null

cocoa-touch - 在 iPad 上处理多个窗口的方向

ios - 从 2 个不同的数组加载 tableview

swift - 如何根据 Swift 中的数据抛出和处理错误?

javascript - 使用 PFCloud 代码推送通知

ios - 在没有 Segue 或程序化调用的情况下分配委托(delegate)

ios - 重复动画重新启动按钮的位置

ios - 如何以编程方式快速发送手势

swift - UITextView:添加GestureRecognizer并找到textView的标签