I try to create an attribute string from a html response to show it on a label. But, when I created the string, I am facing some issues. The conversion removes the newline characters from the string.
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))
I want to assign this attributed string to a label. But it doesn't shows the text with line breaks. Please, help me to solve this
Replace all \n with <br>. <br> is the html tag for new line. 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)
}

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With