Search code examples
swiftnsattributedstring

How to transfer HTML text into an attributed string without losing line breaks in Swift 3


Please do not mark as duplicate. None of the existing questions solves not losing line breaks.

Given String: "Regular text becomes <b>bold with&nbsp;</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.


Solution

  • Try set numberOfLines property in the UILabel.

    For that, you can count the number of break lines and set into numberOfLines.

    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
    
            self.numberOfLines = htmlText.components(separatedBy: "\n").count
        }
    }
    

    I hope this example help you.