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

时间:2017-04-11 23:14:33

标签: swift nsattributedstring

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

给定字符串:"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)

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

1 个答案:

答案 0 :(得分:2)

尝试在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
    }
}

我希望这个例子可以帮助你。