请不要标记为重复。现有问题都没有解决没有丢失换行符。
给定字符串:"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)
我错过了什么?我需要做些什么来保持换行符? 非常感谢帮助。
答案 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
}
}
我希望这个例子可以帮助你。