【问题标题】:How to transfer HTML text into an attributed string without losing line breaks in Swift 3 [duplicate]如何在 Swift 3 中将 HTML 文本转换为属性字符串而不丢失换行符 [重复]
【发布时间】:2017-04-11 23:14:33
【问题描述】:

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

给定字符串:"Regular text becomes <b>bold with </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)

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

【问题讨论】:

  • @LeoDabus 我试过把using: .unicode改成using: .utf8,还是一样。
  • 我刚刚更新了答案。如果你使用得当,它会起作用。
  • @LeoDabus 仍然无法正常工作
  • 好吧。这样就解决了,呵呵。 @LeoDabus,因为你看起来非常适合,你能告诉我,改变行之间的空间using my code,我要补充什么?
  • 只需添加&lt;br&gt;&lt;br&gt; :)

标签: swift nsattributedstring


【解决方案1】:

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

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

【讨论】:

  • 没有帮助。不幸的是
  • 我刚刚测试了这段代码,对我来说效果很好。发生了什么事?
猜你喜欢
  • 1970-01-01
  • 2016-11-23
  • 1970-01-01
  • 2018-02-05
  • 2012-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多