NSAttributedString and html styling (bullet alignment)

I had to add custom styles to a list and this is the paragraph style I ended up using for each bullet in an NSAttributedString

The headIndent and firstLineHeadIndent can be changed but the NSTextTab location should be the same as headIndent

NSMutableParagraphStyle *const bulletParagraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
bulletParagraphStyle.headIndent = 60;
bulletParagraphStyle.firstLineHeadIndent = 30;
NSTextTab *listTab = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentNatural location:60 options:@{}];
bulletParagraphStyle.tabStops = @[listTab];

This works assuming your bullet point has a \t after it (and then then text)


Use <table> instead of <ul><li> to handle the bullet alignment. Styles like ul{margin:0;padding:0} or li{margin-left: 0;} will be ignored.

Example:

let html = "<table>" +
            "<tr><td valign=\"top\" style=\"padding-right:16px\">•</td><td valign=\"top\">text 1</td></tr>" +
            "<tr><td valign=\"top\" style=\"padding-right:16px\">•</td><td valign=\"top\">text 2</td></tr>" +
            "</table>"

let attributedString = try! NSAttributedString(data: html.data(using: String.Encoding.utf8)!,
                               options: [.documentType: NSAttributedString.DocumentType.html,
                                         .characterEncoding: String.Encoding.utf8.rawValue,],
                               documentAttributes: nil)