How to wrap HTML text in an attribute string without losing line breaks in Swift 3

Please do not mark as duplicate. None of the existing issues decides not to break line breaks.

Given the line: "Regular text becomes <b>bold with&nbsp;</b>\n\n<b><i>An italic</i></b>\n\n<b>Linebreak</b>"

I have two options:

 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) 

This option loses font, size and . Line break.

The next extension from this answer retains the UILabel font, but also loses line breaks.

 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) 

What am I missing? What do I need to do to keep line breaks? Help is much appreciated.

0
swift nsattributedstring
source share
1 answer

Try setting the numberOfLines property to UILabel.

To do this, you can count the number of interrupt lines and set to 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 } } 

I hope this example helps you.

+2
source share

All Articles