Search code examples
iosnsattributedstring

How to remove padding under last paragraph from NSAttributedString created from HTML using NSHTMLTextDocumentType


When creating an NSAttributedString from HTML, using NSHTMLTextDocumentType, I'm finding it will add an \n for each paragraph even after the last paragraph. This is adding undesired padding underneath the last paragraph of text that's shown in a UILabel. How does one remove that extra padding for the last paragraph only?

NSString *style = @"<style> body { font-family: Avenir; font-size: 18px; color: blue; } p:last-of-type { margin: 0; }</style>";
NSString *html = @"<p>A whole bunch of sample text goes right here.</p><p>Now here's another paragraph that unfortunately has an extra line underneath the text adding undesired padding to the label. :(</p>";
NSString *styledHtml = [NSString stringWithFormat:@"%@%@", style, html];

self.label.attributedText = [[NSMutableAttributedString alloc] initWithData:[styledHtml dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];

enter image description here enter image description here


Solution

  • Swift 4 version:

    Since you are using an NSMutableAttributedString object you can remove the newline character at the end (if it exists) like this:

    if let lastCharacter = attrStr.string.last, lastCharacter == "\n" {
        attrStr.deleteCharacters(in: NSRange(location: attrStr.length-1, length: 1))
    }
    

    The reason for the extra newline character seems to originate from the way xmllib processes the html. It wraps the "tagless" string into a <p> tag and the tag adds a newline character by default.