Please do not mark as duplicate. None of the existing questions solves not losing line breaks.
Given String: "Regular text becomes <b>bold with </b>\n\n<b><i>An italic</i></b>\n\n<b>Linebreak</b>"
I have two options:
let attrStr = try! NSAttributedString(
data: story.body.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSFontAttributeName: Handler.shared.setFont(FontNames.sourceSerifProRegular, 25.0)],
documentAttributes: nil)
This option loses the font, size and the line breaks.
The following extension from this answer, keeps UILabel
's font, but it loses the line breaks as well.
extension UILabel {
func _slpGetSize() -> CGSize? {
return (text as NSString?)?.size(attributes: [NSFontAttributeName: font])
}
func setHTMLFromString(htmlText: String) {
let modifiedFont = NSString(format:"<span style=\"font-family: \(self.font!.fontName); font-size: \(self.font!.pointSize)\">%@</span>" as NSString, htmlText) as String
let attrStr = try! NSAttributedString(
data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
documentAttributes: nil)
self.attributedText = attrStr
}
}
label.setHTMLFromString(htmlText: story.body)
What am I missing? What do I need to do to keep the line breaks? Help is very appreciated.
` not `\n` – Leo Dabus Apr 12 '17 at 00:27
` :) – Leo Dabus Apr 12 '17 at 00:37
tag before converting HTML text into an attributed string. For instance, here you can do the following story.body.replacingOccurrences(of: "\n", with: "
") . Now you can safely convert HTML text into an attributed string. – Mohammad Daihan Jul 27 '22 at 05:42