Apply Custom font to Attributed string Which Converts from HTML String

前端 未结 1 1023
说谎
说谎 2020-12-03 12:00

I used UITextView in which i display NSAttributedString. i got HTML string from server . I converted HTML to NSAttributedString us

相关标签:
1条回答
  • 2020-12-03 12:15

    Finally i got answer. you can check larmes answer(Find attributes from attributed string that user typed) or you can simply remove old font attribute and apply new font using below code.

     NSDictionary *dictAttrib = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,  NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};
     NSMutableAttributedString *attrib = [[NSMutableAttributedString alloc]initWithData:[yourHTMLString dataUsingEncoding:NSUTF8StringEncoding] options:dictAttrib documentAttributes:nil error:nil];
     [attrib beginEditing];
            [attrib enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attrib.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
                if (value) {
                    UIFont *oldFont = (UIFont *)value;
                    NSLog(@"%@",oldFont.fontName);
    
                    /*----- Remove old font attribute -----*/
                    [attrib removeAttribute:NSFontAttributeName range:range];
                    //replace your font with new.
                    /*----- Add new font attribute -----*/
                    if ([oldFont.fontName isEqualToString:@"TimesNewRomanPSMT"])
                        [attrib addAttribute:NSFontAttributeName value:font1 range:range];
                    else if([oldFont.fontName isEqualToString:@"TimesNewRomanPS-BoldMT"])
                        [attrib addAttribute:NSFontAttributeName value:font2 range:range];
                    else if([oldFont.fontName isEqualToString:@"TimesNewRomanPS-ItalicMT"])
                        [attrib addAttribute:NSFontAttributeName value:font3 range:range];
                    else if([oldFont.fontName isEqualToString:@"TimesNewRomanPS-BoldItalicMT"])
                        [attrib addAttribute:NSFontAttributeName value:font4 range:range];
                    else
                        [attrib addAttribute:NSFontAttributeName value:font5 range:range];
                }
            }];
    [attrib endEditing];
    

    Thanks. Maybe it will help you.

    0 讨论(0)
提交回复
热议问题