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

泄露秘密 提交于 2019-12-13 07:19:40

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/43357701/how-to-transfer-html-text-into-an-attributed-string-without-losing-line-breaks-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!