phil phil - 1 year ago 137
HTML Question

Parsing HTML into NSAttributedText - how to set font?

I am trying to get a snippet of text that is formatted in html to display nicely on an iPhone in a UITableViewCell.

So far I have this:

NSError* error;
NSString* source = @"<strong>Nice</strong> try, Phil";
NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithData:[source dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
documentAttributes:nil error:&error];

This kind of works. I get some text that has 'Nice' in bold! But... it also sets the font to be Times Roman! This is not the font face I want.
I am thinking I need to set something in the documentAttributes, but, I can't find any examples anywhere.

Answer Source

Figured it out. Bit of a bear, and maybe not the best answer.

This code will go through all the font changes. I know that it is using "Times New Roman" and "Times New Roman BoldMT" for the fonts. But regardless, this will find the bold fonts and let me reset them. I can also reset the size while I'm at it.

I honestly hope/think there is a way to set this up at parse time, but I can't find it if there is.

    NSRange range = (NSRange){0,[str length]};
    [str enumerateAttribute:NSFontAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) {
        UIFont* currentFont = value;
        UIFont *replacementFont = nil;

        if ([currentFont.fontName rangeOfString:@"bold" options:NSCaseInsensitiveSearch].location != NSNotFound) {
            replacementFont = [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:25.0f];
        } else {
            replacementFont = [UIFont fontWithName:@"HelveticaNeue-Thin" size:25.0f];

        [str addAttribute:NSFontAttributeName value:replacementFont range:range];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download