且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

解析HTML到NSAttributedText - 如何设置字体?

更新时间:2023-11-07 09:17:28



这段代码将经历所有的字体变化。我知道它使用Times New Roman和Times New Roman BoldMT作为字体。
但无论如何,这会找到大胆的字体,让我重置它们。我可以重置大小,而我在它。



我真的希望/认为有一种方法可以在解析时设置它,但我不能找到它。

  NSRange range =(NSRange){0,[str length]}; 
[STR enumerateAttribute:NSFontAttributeName INRANGE:范围选择:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(值id,NSRange范围,BOOL *停止){
UIFont * currentFont =值;
UIFont * replacementFont = nil;如果

([currentFont.fontName rangeOfString:@ 大胆 的选项:NSCaseInsensitiveSearch]!.location = NSNotFound){
replacementFont = [UIFont fontWithName:@ HelveticaNeue-CondensedBold 尺寸:25.0 F];
} else {
replacementFont = [UIFont fontWithName:@HelveticaNeue-Thinsize:25.0f];
}

[str addAttribute:NSFontAttributeName value:replacementFont range:range];
}];


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.

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];
    }];