如何将 HTML 文本转换为属性字符串而不丢失 Swift 中的换行符 3

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

请不要标记为重复。 None 的现有问题解决了 不丢失换行符

给定字符串:"Regular text becomes <b>bold with&nbsp;</b>\n\n<b><i>An italic</i></b>\n\n<b>Linebreak</b>"

我有两个选择:

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)

此选项丢失字体、字号换行

下面的extension from this answer,保留了UILabel的字体,但也去掉了换行符。

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)

我错过了什么?我需要做什么来保持换行符? 非常感谢帮助。

尝试在 UILabel 中设置 numberOfLines 属性。

为此,您可以计算断线的数量并设置到 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
    }
}

希望这个例子对你有帮助。