【发布时间】:2017-04-11 23:14:33
【问题描述】:
请不要标记为重复。现有问题都没有解决不丢失换行符。
给定字符串:"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)
我错过了什么?我需要做什么来保持换行符? 非常感谢您的帮助。
【问题讨论】:
-
@LeoDabus 我试过把
using: .unicode改成using: .utf8,还是一样。 -
我刚刚更新了答案。如果你使用得当,它会起作用。
-
@LeoDabus 仍然无法正常工作
-
好吧。这样就解决了,呵呵。 @LeoDabus,因为你看起来非常适合,你能告诉我,改变行之间的空间
using my code,我要补充什么? -
只需添加
<br><br>:)