Objective c 目标c-HTML到NSAttribute字符串

Objective c 目标c-HTML到NSAttribute字符串,objective-c,nsattributedstring,Objective C,Nsattributedstring,我编写了一个函数,可以将HTML文本转换为NSAttributedString。它工作得很好。然而,我注意到一些标记嵌套在另一个标记中时,它们的字体会被覆盖 这是我的密码 +(NSMutableAttributedString*) replaceHTMLTags : (NSString*) text : (NSString*) fontName : (CGFloat) fontSize { UIFont* font = [UIFont fontWithName:fontName size

我编写了一个函数,可以将HTML文本转换为
NSAttributedString
。它工作得很好。然而,我注意到一些标记嵌套在另一个标记中时,它们的字体会被覆盖

这是我的密码

+(NSMutableAttributedString*) replaceHTMLTags : (NSString*) text : (NSString*) fontName : (CGFloat) fontSize
{
    UIFont* font = [UIFont fontWithName:fontName size:fontSize];
    NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentJustified;

    text = [text stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"];
    NSMutableAttributedString* finalText = [[NSMutableAttributedString alloc]initWithString:text];

    [finalText setAttributes:@{NSFontAttributeName:font} range:NSMakeRange(0, [finalText string].length)];

    finalText = [self recurseFunc:finalText :@"" : font : paragraphStyle];
    return finalText;
}

+(NSMutableAttributedString*) recurseFunc : (NSMutableAttributedString*) text : (NSString*) tag : (UIFont*) font : (NSMutableParagraphStyle*) paragraphStyle
{
    NSMutableAttributedString* finalText = text;

    NSRange newOpenTagRange;
    //RECURSE IF THERE ARE MORE TAGS
    while((newOpenTagRange = [[text string] rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
    {
        NSString* openTagName = [[text string] substringWithRange:newOpenTagRange];
        NSString* closeTagName = [self getCloseTagName: openTagName];
        NSRange newCloseTagRange = [[text string ]rangeOfString:closeTagName];

        if(newCloseTagRange.location != NSNotFound)
        {
            NSString* textWithTags = [[text string] substringWithRange:NSMakeRange(newOpenTagRange.location, newCloseTagRange.location - newOpenTagRange.location + newCloseTagRange.length)];
            NSString* newPlainText = [textWithTags stringByReplacingOccurrencesOfString:openTagName withString:@""];
            newPlainText = [newPlainText stringByReplacingOccurrencesOfString:closeTagName withString:@""];

            NSMutableAttributedString* newText = [[NSMutableAttributedString alloc]initWithString:newPlainText attributes:@{NSFontAttributeName:font,  NSParagraphStyleAttributeName:paragraphStyle}];

            newText = [self recurseFunc:newText :openTagName : font : paragraphStyle];
            [finalText replaceCharactersInRange:NSMakeRange(newOpenTagRange.location, newCloseTagRange.location - newOpenTagRange.location + newCloseTagRange.length) withAttributedString:newText];
        }
        else
        {
            NSLog(@"Cannot find closing tag for tag %@", openTagName);
        }
    }

    //FORMAT HTML TAGS
    if([tag containsString:@"<p"])
    {
        [finalText.mutableString appendString:@"\n\n"];
    }

    else if ([tag isEqualToString:@"<i>"])
    {
        UIFont* italicFont = [UIFont fontWithName:@"Arial-ItalicMT" size:DEFAULT_FONT_SIZE];
        [finalText addAttribute:NSFontAttributeName value:italicFont range:NSMakeRange(0, [finalText string].length)];
    }
    else if ([tag isEqualToString:@"<b>"])
    {
        UIFont* boldFont = [UIFont fontWithName:@"Arial-BoldMT" size:DEFAULT_FONT_SIZE];
        [finalText addAttribute:NSFontAttributeName value:boldFont range:NSMakeRange(0, [finalText string].length)];

    }
    else if([tag isEqualToString:@"<ul>"])
    {
        NSMutableParagraphStyle* tempStyle = [[NSMutableParagraphStyle alloc]init];
        tempStyle.headIndent = 30;
        tempStyle.firstLineHeadIndent = 10;
        tempStyle.lineBreakMode = NSLineBreakByWordWrapping;
        tempStyle.alignment = NSTextAlignmentJustified;

        NSString* temp = [[finalText string]stringByReplacingOccurrencesOfString:@"###" withString:@"•\t"];
        temp = [NSString stringWithFormat:@"\n%@", temp];
        [finalText setAttributedString:[[NSAttributedString alloc] initWithString:temp]];

        [finalText addAttribute:NSParagraphStyleAttributeName value:tempStyle range:NSMakeRange(0, [finalText string].length)];


    }
    else if ([tag isEqualToString:@"<li>"])
    {
        NSMutableAttributedString* tempAS = [[NSMutableAttributedString alloc]initWithString:@"###$$$\n"];
        NSRange r = [[tempAS string]rangeOfString:@"$$$"];
        [tempAS replaceCharactersInRange:r withAttributedString:finalText];
        [finalText setAttributedString:tempAS];

    }
    return finalText;
}
+(NSMutableAttributedString*)替换HtmlTags:(NSString*)文本:(NSString*)fontName:(CGFloat)fontSize
{
UIFont*font=[UIFont fontWithName:fontName size:fontSize];
NSMutableParagraphStyle*paragraphStyle=[[NSMutableParagraphStyle alloc]init];
paragraphStyle.lineBreakMode=NSLineBreakByWordWrapping;
paragraphStyle.alignment=NSTextAlignmentJustified;
text=[text stringByReplacingOccurrencesOfString:@“
”with string:@“\n”]; NSMutableAttributedString*finalText=[[NSMutableAttributedString alloc]initWithString:text]; [finalText setAttributes:@{NSFontAttributeName:font}范围:NSMakeRange(0[finalText string].length]); finalText=[自递归函数:finalText:@”“:字体:段落样式]; 返回finalText; } +(NSMutableAttributedString*)递归函数:(NSMutableAttributedString*)文本:(NSString*)标记:(UIFont*)字体:(NSMutableParagraphStyle*)段落样式 { NSMutableAttributeString*finalText=文本; NSRange newOpenTagRange; //如果有更多标记,则递归 while((newOpenTagRange=[[text string]rangeOfString:@“]+>”选项:NSRegularExpressionSearch])。位置!=NSNotFound) { NSString*openTagName=[[text string]substringWithRange:newOpenTagRange]; NSString*closeTagName=[self-getCloseTagName:openTagName]; NSRange newCloseTagRange=[[text string]rangeOfString:closeTagName]; if(newCloseTagRange.location!=NSNotFound) { NSString*textWithTags=[[text string]substringWithRange:NSMakeRange(newOpenTagRange.location,newCloseTagRange.location-newOpenTagRange.location+newCloseTagRange.length)]; NSString*newPlainText=[textWithTags stringByReplacingOccurrencesOfString:openTagName withString:@”“]; newPlainText=[newPlainText stringByReplacingOccurrencesOfString:closeTagName with String:@”“]; NSMUTABLeAttributeString*newText=[[NSMUTABLeAttributeString alloc]initWithString:newPlainText属性:@{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle}]; newText=[自递归函数:newText:openTagName:font:paragraphStyle]; [finalText-ReplaceCharactersRange:nsMakerRange(newOpenTagRange.location,newCloseTagRange.location-newOpenTagRange.location+newCloseTagRange.length)和AttributeString:newText]; } 其他的 { NSLog(@“找不到标记%@的结束标记”,openTagName); } } //格式化HTML标记
如果([tag containssString:@“用于将HTML转换为
NSAttributedString
,则可以使用以下代码:

[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] 
                             options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                       NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} 
                  documentAttributes:nil error:nil];

没有测试您的全部代码,但是快速查看,我猜如果不使用斜体和粗体,someText将无法工作。@Larme我已经测试了整个代码。一切正常。问题是在这样的情况下。
  • someText
    • .Where”Text“不会变为粗体。但是,如果它只是
      一些文本,它就可以正常工作。替换
      NSString*temp=[[finalText-string]stringByReplacingOccurrencesOfString:@“#####”with string:@“•\t”];temp=[NSString stringWithFormat:@“\n%@”,temp];[finalText-setAttributedString:[[NSAttributedString]initWithString:temp]]
      [finalText ReplaceCharactersRange:[[finalText string]rangeOfString:@“######”]withString:@“•\t”];
      这应该解决问题的一部分。第二个问题在于:
      NSMutableAttributedString*newText=[[NSMutableAttributedString alloc]initWithString:newPlainText属性:@{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle}];
      您正在覆盖字体,因此如果字体为“Arial Bold”,它将被参数中的字体覆盖。您好,只是一个小问题,为什么不能使用此解决方案?